diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/__init__.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/__init__.py index d916a9434d8..2ffb9868aed 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/__init__.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/__init__.py @@ -1,26 +1,26 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._cosmos_db_management_client import CosmosDBManagementClient -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "CosmosDBManagementClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._cosmos_db_management_client import CosmosDBManagementClient +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "CosmosDBManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/_configuration.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/_configuration.py index c5add8e600d..94ecc65212d 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/_configuration.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/_configuration.py @@ -1,65 +1,65 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, TYPE_CHECKING - -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy - -from ._version import VERSION - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core.credentials import TokenCredential - - -class CosmosDBManagementClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long - """Configuration for CosmosDBManagementClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str - :keyword api_version: Api Version. Default value is "2024-09-01-preview". Note that overriding - this default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "2024-09-01-preview") - - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - if subscription_id is None: - raise ValueError("Parameter 'subscription_id' must not be None.") - - self.credential = credential - self.subscription_id = subscription_id - self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) - kwargs.setdefault("sdk_moniker", "mgmt-cosmosdb/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - if self.credential and not self.authentication_policy: - self.authentication_policy = ARMChallengeAuthenticationPolicy( - self.credential, *self.credential_scopes, **kwargs - ) +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING + +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class CosmosDBManagementClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long + """Configuration for CosmosDBManagementClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2024-09-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + api_version: str = kwargs.pop("api_version", "2024-09-01-preview") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-cosmosdb/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/_cosmos_db_management_client.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/_cosmos_db_management_client.py index 35832cc34da..dcbf52885a1 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/_cosmos_db_management_client.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/_cosmos_db_management_client.py @@ -1,378 +1,378 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING -from typing_extensions import Self - -from azure.core.pipeline import policies -from azure.core.rest import HttpRequest, HttpResponse -from azure.mgmt.core import ARMPipelineClient -from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy - -from . import models as _models -from ._configuration import CosmosDBManagementClientConfiguration -from ._serialization import Deserializer, Serializer -from .operations import ( - CassandraClustersOperations, - CassandraDataCentersOperations, - CassandraResourcesOperations, - ChaosFaultOperations, - CollectionOperations, - CollectionPartitionOperations, - CollectionPartitionRegionOperations, - CollectionRegionOperations, - DataTransferJobsOperations, - DatabaseAccountRegionOperations, - DatabaseAccountsOperations, - DatabaseOperations, - GraphResourcesOperations, - GremlinResourcesOperations, - LocationsOperations, - MongoDBResourcesOperations, - NetworkSecurityPerimeterConfigurationsOperations, - NotebookWorkspacesOperations, - Operations, - PartitionKeyRangeIdOperations, - PartitionKeyRangeIdRegionOperations, - PercentileOperations, - PercentileSourceTargetOperations, - PercentileTargetOperations, - PrivateEndpointConnectionsOperations, - PrivateLinkResourcesOperations, - RestorableDatabaseAccountsOperations, - RestorableGremlinDatabasesOperations, - RestorableGremlinGraphsOperations, - RestorableGremlinResourcesOperations, - RestorableMongodbCollectionsOperations, - RestorableMongodbDatabasesOperations, - RestorableMongodbResourcesOperations, - RestorableSqlContainersOperations, - RestorableSqlDatabasesOperations, - RestorableSqlResourcesOperations, - RestorableTableResourcesOperations, - RestorableTablesOperations, - ServiceOperations, - SqlResourcesOperations, - TableResourcesOperations, - ThroughputPoolAccountOperations, - ThroughputPoolAccountsOperations, - ThroughputPoolOperations, - ThroughputPoolsOperations, -) - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core.credentials import TokenCredential - - -class CosmosDBManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes - """Azure Cosmos DB Database Service Resource Provider REST API. - - :ivar database_accounts: DatabaseAccountsOperations operations - :vartype database_accounts: azure.mgmt.cosmosdb.operations.DatabaseAccountsOperations - :ivar operations: Operations operations - :vartype operations: azure.mgmt.cosmosdb.operations.Operations - :ivar database: DatabaseOperations operations - :vartype database: azure.mgmt.cosmosdb.operations.DatabaseOperations - :ivar collection: CollectionOperations operations - :vartype collection: azure.mgmt.cosmosdb.operations.CollectionOperations - :ivar collection_region: CollectionRegionOperations operations - :vartype collection_region: azure.mgmt.cosmosdb.operations.CollectionRegionOperations - :ivar database_account_region: DatabaseAccountRegionOperations operations - :vartype database_account_region: - azure.mgmt.cosmosdb.operations.DatabaseAccountRegionOperations - :ivar percentile_source_target: PercentileSourceTargetOperations operations - :vartype percentile_source_target: - azure.mgmt.cosmosdb.operations.PercentileSourceTargetOperations - :ivar percentile_target: PercentileTargetOperations operations - :vartype percentile_target: azure.mgmt.cosmosdb.operations.PercentileTargetOperations - :ivar percentile: PercentileOperations operations - :vartype percentile: azure.mgmt.cosmosdb.operations.PercentileOperations - :ivar collection_partition_region: CollectionPartitionRegionOperations operations - :vartype collection_partition_region: - azure.mgmt.cosmosdb.operations.CollectionPartitionRegionOperations - :ivar collection_partition: CollectionPartitionOperations operations - :vartype collection_partition: azure.mgmt.cosmosdb.operations.CollectionPartitionOperations - :ivar partition_key_range_id: PartitionKeyRangeIdOperations operations - :vartype partition_key_range_id: azure.mgmt.cosmosdb.operations.PartitionKeyRangeIdOperations - :ivar partition_key_range_id_region: PartitionKeyRangeIdRegionOperations operations - :vartype partition_key_range_id_region: - azure.mgmt.cosmosdb.operations.PartitionKeyRangeIdRegionOperations - :ivar graph_resources: GraphResourcesOperations operations - :vartype graph_resources: azure.mgmt.cosmosdb.operations.GraphResourcesOperations - :ivar sql_resources: SqlResourcesOperations operations - :vartype sql_resources: azure.mgmt.cosmosdb.operations.SqlResourcesOperations - :ivar mongo_db_resources: MongoDBResourcesOperations operations - :vartype mongo_db_resources: azure.mgmt.cosmosdb.operations.MongoDBResourcesOperations - :ivar table_resources: TableResourcesOperations operations - :vartype table_resources: azure.mgmt.cosmosdb.operations.TableResourcesOperations - :ivar cassandra_resources: CassandraResourcesOperations operations - :vartype cassandra_resources: azure.mgmt.cosmosdb.operations.CassandraResourcesOperations - :ivar gremlin_resources: GremlinResourcesOperations operations - :vartype gremlin_resources: azure.mgmt.cosmosdb.operations.GremlinResourcesOperations - :ivar locations: LocationsOperations operations - :vartype locations: azure.mgmt.cosmosdb.operations.LocationsOperations - :ivar data_transfer_jobs: DataTransferJobsOperations operations - :vartype data_transfer_jobs: azure.mgmt.cosmosdb.operations.DataTransferJobsOperations - :ivar cassandra_clusters: CassandraClustersOperations operations - :vartype cassandra_clusters: azure.mgmt.cosmosdb.operations.CassandraClustersOperations - :ivar cassandra_data_centers: CassandraDataCentersOperations operations - :vartype cassandra_data_centers: azure.mgmt.cosmosdb.operations.CassandraDataCentersOperations - :ivar network_security_perimeter_configurations: - NetworkSecurityPerimeterConfigurationsOperations operations - :vartype network_security_perimeter_configurations: - azure.mgmt.cosmosdb.operations.NetworkSecurityPerimeterConfigurationsOperations - :ivar notebook_workspaces: NotebookWorkspacesOperations operations - :vartype notebook_workspaces: azure.mgmt.cosmosdb.operations.NotebookWorkspacesOperations - :ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations - :vartype private_endpoint_connections: - azure.mgmt.cosmosdb.operations.PrivateEndpointConnectionsOperations - :ivar private_link_resources: PrivateLinkResourcesOperations operations - :vartype private_link_resources: azure.mgmt.cosmosdb.operations.PrivateLinkResourcesOperations - :ivar restorable_database_accounts: RestorableDatabaseAccountsOperations operations - :vartype restorable_database_accounts: - azure.mgmt.cosmosdb.operations.RestorableDatabaseAccountsOperations - :ivar restorable_sql_databases: RestorableSqlDatabasesOperations operations - :vartype restorable_sql_databases: - azure.mgmt.cosmosdb.operations.RestorableSqlDatabasesOperations - :ivar restorable_sql_containers: RestorableSqlContainersOperations operations - :vartype restorable_sql_containers: - azure.mgmt.cosmosdb.operations.RestorableSqlContainersOperations - :ivar restorable_sql_resources: RestorableSqlResourcesOperations operations - :vartype restorable_sql_resources: - azure.mgmt.cosmosdb.operations.RestorableSqlResourcesOperations - :ivar restorable_mongodb_databases: RestorableMongodbDatabasesOperations operations - :vartype restorable_mongodb_databases: - azure.mgmt.cosmosdb.operations.RestorableMongodbDatabasesOperations - :ivar restorable_mongodb_collections: RestorableMongodbCollectionsOperations operations - :vartype restorable_mongodb_collections: - azure.mgmt.cosmosdb.operations.RestorableMongodbCollectionsOperations - :ivar restorable_mongodb_resources: RestorableMongodbResourcesOperations operations - :vartype restorable_mongodb_resources: - azure.mgmt.cosmosdb.operations.RestorableMongodbResourcesOperations - :ivar restorable_gremlin_databases: RestorableGremlinDatabasesOperations operations - :vartype restorable_gremlin_databases: - azure.mgmt.cosmosdb.operations.RestorableGremlinDatabasesOperations - :ivar restorable_gremlin_graphs: RestorableGremlinGraphsOperations operations - :vartype restorable_gremlin_graphs: - azure.mgmt.cosmosdb.operations.RestorableGremlinGraphsOperations - :ivar restorable_gremlin_resources: RestorableGremlinResourcesOperations operations - :vartype restorable_gremlin_resources: - azure.mgmt.cosmosdb.operations.RestorableGremlinResourcesOperations - :ivar restorable_tables: RestorableTablesOperations operations - :vartype restorable_tables: azure.mgmt.cosmosdb.operations.RestorableTablesOperations - :ivar restorable_table_resources: RestorableTableResourcesOperations operations - :vartype restorable_table_resources: - azure.mgmt.cosmosdb.operations.RestorableTableResourcesOperations - :ivar service: ServiceOperations operations - :vartype service: azure.mgmt.cosmosdb.operations.ServiceOperations - :ivar throughput_pools: ThroughputPoolsOperations operations - :vartype throughput_pools: azure.mgmt.cosmosdb.operations.ThroughputPoolsOperations - :ivar throughput_pool: ThroughputPoolOperations operations - :vartype throughput_pool: azure.mgmt.cosmosdb.operations.ThroughputPoolOperations - :ivar throughput_pool_accounts: ThroughputPoolAccountsOperations operations - :vartype throughput_pool_accounts: - azure.mgmt.cosmosdb.operations.ThroughputPoolAccountsOperations - :ivar throughput_pool_account: ThroughputPoolAccountOperations operations - :vartype throughput_pool_account: - azure.mgmt.cosmosdb.operations.ThroughputPoolAccountOperations - :ivar chaos_fault: ChaosFaultOperations operations - :vartype chaos_fault: azure.mgmt.cosmosdb.operations.ChaosFaultOperations - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str - :param base_url: Service URL. Default value is "https://management.azure.com". - :type base_url: str - :keyword api_version: Api Version. Default value is "2024-09-01-preview". Note that overriding - this default value may result in unsupported behavior. - :paramtype api_version: str - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - """ - - def __init__( - self, - credential: "TokenCredential", - subscription_id: str, - base_url: str = "https://management.azure.com", - **kwargs: Any - ) -> None: - self._config = CosmosDBManagementClientConfiguration( - credential=credential, subscription_id=subscription_id, **kwargs - ) - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - ARMAutoResourceProviderRegistrationPolicy(), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, policies=_policies, **kwargs) - - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) - self._serialize.client_side_validation = False - self.database_accounts = DatabaseAccountsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) - self.database = DatabaseOperations(self._client, self._config, self._serialize, self._deserialize) - self.collection = CollectionOperations(self._client, self._config, self._serialize, self._deserialize) - self.collection_region = CollectionRegionOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.database_account_region = DatabaseAccountRegionOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.percentile_source_target = PercentileSourceTargetOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.percentile_target = PercentileTargetOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.percentile = PercentileOperations(self._client, self._config, self._serialize, self._deserialize) - self.collection_partition_region = CollectionPartitionRegionOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.collection_partition = CollectionPartitionOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.partition_key_range_id = PartitionKeyRangeIdOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.partition_key_range_id_region = PartitionKeyRangeIdRegionOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.graph_resources = GraphResourcesOperations(self._client, self._config, self._serialize, self._deserialize) - self.sql_resources = SqlResourcesOperations(self._client, self._config, self._serialize, self._deserialize) - self.mongo_db_resources = MongoDBResourcesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.table_resources = TableResourcesOperations(self._client, self._config, self._serialize, self._deserialize) - self.cassandra_resources = CassandraResourcesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.gremlin_resources = GremlinResourcesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.locations = LocationsOperations(self._client, self._config, self._serialize, self._deserialize) - self.data_transfer_jobs = DataTransferJobsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.cassandra_clusters = CassandraClustersOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.cassandra_data_centers = CassandraDataCentersOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.network_security_perimeter_configurations = NetworkSecurityPerimeterConfigurationsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.notebook_workspaces = NotebookWorkspacesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.private_endpoint_connections = PrivateEndpointConnectionsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.private_link_resources = PrivateLinkResourcesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.restorable_database_accounts = RestorableDatabaseAccountsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.restorable_sql_databases = RestorableSqlDatabasesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.restorable_sql_containers = RestorableSqlContainersOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.restorable_sql_resources = RestorableSqlResourcesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.restorable_mongodb_databases = RestorableMongodbDatabasesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.restorable_mongodb_collections = RestorableMongodbCollectionsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.restorable_mongodb_resources = RestorableMongodbResourcesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.restorable_gremlin_databases = RestorableGremlinDatabasesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.restorable_gremlin_graphs = RestorableGremlinGraphsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.restorable_gremlin_resources = RestorableGremlinResourcesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.restorable_tables = RestorableTablesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.restorable_table_resources = RestorableTableResourcesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.service = ServiceOperations(self._client, self._config, self._serialize, self._deserialize) - self.throughput_pools = ThroughputPoolsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.throughput_pool = ThroughputPoolOperations(self._client, self._config, self._serialize, self._deserialize) - self.throughput_pool_accounts = ThroughputPoolAccountsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.throughput_pool_account = ThroughputPoolAccountOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.chaos_fault = ChaosFaultOperations(self._client, self._config, self._serialize, self._deserialize) - - def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = client._send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - def close(self) -> None: - self._client.close() - - def __enter__(self) -> Self: - self._client.__enter__() - return self - - def __exit__(self, *exc_details: Any) -> None: - self._client.__exit__(*exc_details) +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, TYPE_CHECKING +from typing_extensions import Self + +from azure.core.pipeline import policies +from azure.core.rest import HttpRequest, HttpResponse +from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy + +from . import models as _models +from ._configuration import CosmosDBManagementClientConfiguration +from ._serialization import Deserializer, Serializer +from .operations import ( + CassandraClustersOperations, + CassandraDataCentersOperations, + CassandraResourcesOperations, + ChaosFaultOperations, + CollectionOperations, + CollectionPartitionOperations, + CollectionPartitionRegionOperations, + CollectionRegionOperations, + DataTransferJobsOperations, + DatabaseAccountRegionOperations, + DatabaseAccountsOperations, + DatabaseOperations, + GraphResourcesOperations, + GremlinResourcesOperations, + LocationsOperations, + MongoDBResourcesOperations, + NetworkSecurityPerimeterConfigurationsOperations, + NotebookWorkspacesOperations, + Operations, + PartitionKeyRangeIdOperations, + PartitionKeyRangeIdRegionOperations, + PercentileOperations, + PercentileSourceTargetOperations, + PercentileTargetOperations, + PrivateEndpointConnectionsOperations, + PrivateLinkResourcesOperations, + RestorableDatabaseAccountsOperations, + RestorableGremlinDatabasesOperations, + RestorableGremlinGraphsOperations, + RestorableGremlinResourcesOperations, + RestorableMongodbCollectionsOperations, + RestorableMongodbDatabasesOperations, + RestorableMongodbResourcesOperations, + RestorableSqlContainersOperations, + RestorableSqlDatabasesOperations, + RestorableSqlResourcesOperations, + RestorableTableResourcesOperations, + RestorableTablesOperations, + ServiceOperations, + SqlResourcesOperations, + TableResourcesOperations, + ThroughputPoolAccountOperations, + ThroughputPoolAccountsOperations, + ThroughputPoolOperations, + ThroughputPoolsOperations, +) + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class CosmosDBManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes + """Azure Cosmos DB Database Service Resource Provider REST API. + + :ivar database_accounts: DatabaseAccountsOperations operations + :vartype database_accounts: azure.mgmt.cosmosdb.operations.DatabaseAccountsOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.cosmosdb.operations.Operations + :ivar database: DatabaseOperations operations + :vartype database: azure.mgmt.cosmosdb.operations.DatabaseOperations + :ivar collection: CollectionOperations operations + :vartype collection: azure.mgmt.cosmosdb.operations.CollectionOperations + :ivar collection_region: CollectionRegionOperations operations + :vartype collection_region: azure.mgmt.cosmosdb.operations.CollectionRegionOperations + :ivar database_account_region: DatabaseAccountRegionOperations operations + :vartype database_account_region: + azure.mgmt.cosmosdb.operations.DatabaseAccountRegionOperations + :ivar percentile_source_target: PercentileSourceTargetOperations operations + :vartype percentile_source_target: + azure.mgmt.cosmosdb.operations.PercentileSourceTargetOperations + :ivar percentile_target: PercentileTargetOperations operations + :vartype percentile_target: azure.mgmt.cosmosdb.operations.PercentileTargetOperations + :ivar percentile: PercentileOperations operations + :vartype percentile: azure.mgmt.cosmosdb.operations.PercentileOperations + :ivar collection_partition_region: CollectionPartitionRegionOperations operations + :vartype collection_partition_region: + azure.mgmt.cosmosdb.operations.CollectionPartitionRegionOperations + :ivar collection_partition: CollectionPartitionOperations operations + :vartype collection_partition: azure.mgmt.cosmosdb.operations.CollectionPartitionOperations + :ivar partition_key_range_id: PartitionKeyRangeIdOperations operations + :vartype partition_key_range_id: azure.mgmt.cosmosdb.operations.PartitionKeyRangeIdOperations + :ivar partition_key_range_id_region: PartitionKeyRangeIdRegionOperations operations + :vartype partition_key_range_id_region: + azure.mgmt.cosmosdb.operations.PartitionKeyRangeIdRegionOperations + :ivar graph_resources: GraphResourcesOperations operations + :vartype graph_resources: azure.mgmt.cosmosdb.operations.GraphResourcesOperations + :ivar sql_resources: SqlResourcesOperations operations + :vartype sql_resources: azure.mgmt.cosmosdb.operations.SqlResourcesOperations + :ivar mongo_db_resources: MongoDBResourcesOperations operations + :vartype mongo_db_resources: azure.mgmt.cosmosdb.operations.MongoDBResourcesOperations + :ivar table_resources: TableResourcesOperations operations + :vartype table_resources: azure.mgmt.cosmosdb.operations.TableResourcesOperations + :ivar cassandra_resources: CassandraResourcesOperations operations + :vartype cassandra_resources: azure.mgmt.cosmosdb.operations.CassandraResourcesOperations + :ivar gremlin_resources: GremlinResourcesOperations operations + :vartype gremlin_resources: azure.mgmt.cosmosdb.operations.GremlinResourcesOperations + :ivar locations: LocationsOperations operations + :vartype locations: azure.mgmt.cosmosdb.operations.LocationsOperations + :ivar data_transfer_jobs: DataTransferJobsOperations operations + :vartype data_transfer_jobs: azure.mgmt.cosmosdb.operations.DataTransferJobsOperations + :ivar cassandra_clusters: CassandraClustersOperations operations + :vartype cassandra_clusters: azure.mgmt.cosmosdb.operations.CassandraClustersOperations + :ivar cassandra_data_centers: CassandraDataCentersOperations operations + :vartype cassandra_data_centers: azure.mgmt.cosmosdb.operations.CassandraDataCentersOperations + :ivar network_security_perimeter_configurations: + NetworkSecurityPerimeterConfigurationsOperations operations + :vartype network_security_perimeter_configurations: + azure.mgmt.cosmosdb.operations.NetworkSecurityPerimeterConfigurationsOperations + :ivar notebook_workspaces: NotebookWorkspacesOperations operations + :vartype notebook_workspaces: azure.mgmt.cosmosdb.operations.NotebookWorkspacesOperations + :ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations + :vartype private_endpoint_connections: + azure.mgmt.cosmosdb.operations.PrivateEndpointConnectionsOperations + :ivar private_link_resources: PrivateLinkResourcesOperations operations + :vartype private_link_resources: azure.mgmt.cosmosdb.operations.PrivateLinkResourcesOperations + :ivar restorable_database_accounts: RestorableDatabaseAccountsOperations operations + :vartype restorable_database_accounts: + azure.mgmt.cosmosdb.operations.RestorableDatabaseAccountsOperations + :ivar restorable_sql_databases: RestorableSqlDatabasesOperations operations + :vartype restorable_sql_databases: + azure.mgmt.cosmosdb.operations.RestorableSqlDatabasesOperations + :ivar restorable_sql_containers: RestorableSqlContainersOperations operations + :vartype restorable_sql_containers: + azure.mgmt.cosmosdb.operations.RestorableSqlContainersOperations + :ivar restorable_sql_resources: RestorableSqlResourcesOperations operations + :vartype restorable_sql_resources: + azure.mgmt.cosmosdb.operations.RestorableSqlResourcesOperations + :ivar restorable_mongodb_databases: RestorableMongodbDatabasesOperations operations + :vartype restorable_mongodb_databases: + azure.mgmt.cosmosdb.operations.RestorableMongodbDatabasesOperations + :ivar restorable_mongodb_collections: RestorableMongodbCollectionsOperations operations + :vartype restorable_mongodb_collections: + azure.mgmt.cosmosdb.operations.RestorableMongodbCollectionsOperations + :ivar restorable_mongodb_resources: RestorableMongodbResourcesOperations operations + :vartype restorable_mongodb_resources: + azure.mgmt.cosmosdb.operations.RestorableMongodbResourcesOperations + :ivar restorable_gremlin_databases: RestorableGremlinDatabasesOperations operations + :vartype restorable_gremlin_databases: + azure.mgmt.cosmosdb.operations.RestorableGremlinDatabasesOperations + :ivar restorable_gremlin_graphs: RestorableGremlinGraphsOperations operations + :vartype restorable_gremlin_graphs: + azure.mgmt.cosmosdb.operations.RestorableGremlinGraphsOperations + :ivar restorable_gremlin_resources: RestorableGremlinResourcesOperations operations + :vartype restorable_gremlin_resources: + azure.mgmt.cosmosdb.operations.RestorableGremlinResourcesOperations + :ivar restorable_tables: RestorableTablesOperations operations + :vartype restorable_tables: azure.mgmt.cosmosdb.operations.RestorableTablesOperations + :ivar restorable_table_resources: RestorableTableResourcesOperations operations + :vartype restorable_table_resources: + azure.mgmt.cosmosdb.operations.RestorableTableResourcesOperations + :ivar service: ServiceOperations operations + :vartype service: azure.mgmt.cosmosdb.operations.ServiceOperations + :ivar throughput_pools: ThroughputPoolsOperations operations + :vartype throughput_pools: azure.mgmt.cosmosdb.operations.ThroughputPoolsOperations + :ivar throughput_pool: ThroughputPoolOperations operations + :vartype throughput_pool: azure.mgmt.cosmosdb.operations.ThroughputPoolOperations + :ivar throughput_pool_accounts: ThroughputPoolAccountsOperations operations + :vartype throughput_pool_accounts: + azure.mgmt.cosmosdb.operations.ThroughputPoolAccountsOperations + :ivar throughput_pool_account: ThroughputPoolAccountOperations operations + :vartype throughput_pool_account: + azure.mgmt.cosmosdb.operations.ThroughputPoolAccountOperations + :ivar chaos_fault: ChaosFaultOperations operations + :vartype chaos_fault: azure.mgmt.cosmosdb.operations.ChaosFaultOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2024-09-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = CosmosDBManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + ARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, policies=_policies, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.database_accounts = DatabaseAccountsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.database = DatabaseOperations(self._client, self._config, self._serialize, self._deserialize) + self.collection = CollectionOperations(self._client, self._config, self._serialize, self._deserialize) + self.collection_region = CollectionRegionOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.database_account_region = DatabaseAccountRegionOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.percentile_source_target = PercentileSourceTargetOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.percentile_target = PercentileTargetOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.percentile = PercentileOperations(self._client, self._config, self._serialize, self._deserialize) + self.collection_partition_region = CollectionPartitionRegionOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.collection_partition = CollectionPartitionOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.partition_key_range_id = PartitionKeyRangeIdOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.partition_key_range_id_region = PartitionKeyRangeIdRegionOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.graph_resources = GraphResourcesOperations(self._client, self._config, self._serialize, self._deserialize) + self.sql_resources = SqlResourcesOperations(self._client, self._config, self._serialize, self._deserialize) + self.mongo_db_resources = MongoDBResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.table_resources = TableResourcesOperations(self._client, self._config, self._serialize, self._deserialize) + self.cassandra_resources = CassandraResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.gremlin_resources = GremlinResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.locations = LocationsOperations(self._client, self._config, self._serialize, self._deserialize) + self.data_transfer_jobs = DataTransferJobsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.cassandra_clusters = CassandraClustersOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.cassandra_data_centers = CassandraDataCentersOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.network_security_perimeter_configurations = NetworkSecurityPerimeterConfigurationsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.notebook_workspaces = NotebookWorkspacesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.private_endpoint_connections = PrivateEndpointConnectionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.private_link_resources = PrivateLinkResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.restorable_database_accounts = RestorableDatabaseAccountsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.restorable_sql_databases = RestorableSqlDatabasesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.restorable_sql_containers = RestorableSqlContainersOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.restorable_sql_resources = RestorableSqlResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.restorable_mongodb_databases = RestorableMongodbDatabasesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.restorable_mongodb_collections = RestorableMongodbCollectionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.restorable_mongodb_resources = RestorableMongodbResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.restorable_gremlin_databases = RestorableGremlinDatabasesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.restorable_gremlin_graphs = RestorableGremlinGraphsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.restorable_gremlin_resources = RestorableGremlinResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.restorable_tables = RestorableTablesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.restorable_table_resources = RestorableTableResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.service = ServiceOperations(self._client, self._config, self._serialize, self._deserialize) + self.throughput_pools = ThroughputPoolsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.throughput_pool = ThroughputPoolOperations(self._client, self._config, self._serialize, self._deserialize) + self.throughput_pool_accounts = ThroughputPoolAccountsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.throughput_pool_account = ThroughputPoolAccountOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.chaos_fault = ChaosFaultOperations(self._client, self._config, self._serialize, self._deserialize) + + def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/_patch.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/_patch.py index 04676c9e627..17dbc073e01 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/_patch.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/_patch.py @@ -1,32 +1,32 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - - -# This file is used for handwritten extensions to the generated code. Example: -# https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md -def patch_sdk(): - pass +# coding=utf-8 +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + + +# This file is used for handwritten extensions to the generated code. Example: +# https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md +def patch_sdk(): + pass diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/_serialization.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/_serialization.py index 2e86ccf29e6..8139854b97b 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/_serialization.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/_serialization.py @@ -1,2000 +1,2000 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file -# pyright: reportUnnecessaryTypeIgnoreComment=false - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs -from typing import ( - Dict, - Any, - cast, - Optional, - Union, - AnyStr, - IO, - Mapping, - Callable, - TypeVar, - MutableMapping, - Type, - List, - Mapping, -) - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote -import xml.etree.ElementTree as ET - -import isodate # type: ignore - -from azure.core.exceptions import DeserializationError, SerializationError -from azure.core.serialization import NULL as CoreNull - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -ModelType = TypeVar("ModelType", bound="Model") -JSON = MutableMapping[str, Any] - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) # nosec - except ET.ParseError as err: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise DeserializationError("XML is invalid") from err - elif content_type.startswith("text/"): - return data_as_str - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -try: - from datetime import timezone as _FixedOffset # type: ignore -except ImportError: # Python 2.7 - - class _FixedOffset(datetime.tzinfo): # type: ignore - """Fixed offset in minutes east from UTC. - Copy/pasted from Python doc - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? None: - self.additional_properties: Optional[Dict[str, Any]] = {} - for k in kwargs: - if k not in self._attribute_map: - _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) - elif k in self._validation and self._validation[k].get("readonly", False): - _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) - else: - setattr(self, k, kwargs[k]) - - def __eq__(self, other: Any) -> bool: - """Compare objects by comparing all attributes.""" - if isinstance(other, self.__class__): - return self.__dict__ == other.__dict__ - return False - - def __ne__(self, other: Any) -> bool: - """Compare objects by comparing all attributes.""" - return not self.__eq__(other) - - def __str__(self) -> str: - return str(self.__dict__) - - @classmethod - def enable_additional_properties_sending(cls) -> None: - cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} - - @classmethod - def is_xml_model(cls) -> bool: - try: - cls._xml_map # type: ignore - except AttributeError: - return False - return True - - @classmethod - def _create_xml_node(cls): - """Create XML node.""" - try: - xml_map = cls._xml_map # type: ignore - except AttributeError: - xml_map = {} - - return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) - - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: - """Return the JSON that would be sent to server from this model. - - This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. - - If you want XML serialization, you can pass the kwargs is_xml=True. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :returns: A dict JSON compatible object - :rtype: dict - """ - serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) # type: ignore - - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Callable[[str, Dict[str, Any], Any], Any] = attribute_transformer, - **kwargs: Any - ) -> JSON: - """Return a dict that can be serialized using json.dump. - - Advanced usage might optionally use a callback as parameter: - - .. code::python - - def my_key_transformer(key, attr_desc, value): - return key - - Key is the attribute name used in Python. Attr_desc - is a dict of metadata. Currently contains 'type' with the - msrest type and 'key' with the RestAPI encoded key. - Value is the current value in this object. - - The string returned will be used to serialize the key. - If the return type is a list, this is considered hierarchical - result dict. - - See the three examples in this file: - - - attribute_transformer - - full_restapi_key_transformer - - last_restapi_key_transformer - - If you want XML serialization, you can pass the kwargs is_xml=True. - - :param function key_transformer: A key transformer function. - :returns: A dict JSON compatible object - :rtype: dict - """ - serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs) # type: ignore - - @classmethod - def _infer_class_models(cls): - try: - str_models = cls.__module__.rsplit(".", 1)[0] - models = sys.modules[str_models] - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} - if cls.__name__ not in client_models: - raise ValueError("Not Autorest generated code") - except Exception: - # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. - client_models = {cls.__name__: cls} - return client_models - - @classmethod - def deserialize(cls: Type[ModelType], data: Any, content_type: Optional[str] = None) -> ModelType: - """Parse a str using the RestAPI syntax and return a model. - - :param str data: A str using RestAPI structure. JSON by default. - :param str content_type: JSON by default, set application/xml if XML. - :returns: An instance of this model - :raises: DeserializationError if something went wrong - """ - deserializer = Deserializer(cls._infer_class_models()) - return deserializer(cls.__name__, data, content_type=content_type) # type: ignore - - @classmethod - def from_dict( - cls: Type[ModelType], - data: Any, - key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, - content_type: Optional[str] = None, - ) -> ModelType: - """Parse a dict using given key extractor return a model. - - By default consider key - extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor - and last_rest_key_case_insensitive_extractor) - - :param dict data: A dict using RestAPI structure - :param str content_type: JSON by default, set application/xml if XML. - :returns: An instance of this model - :raises: DeserializationError if something went wrong - """ - deserializer = Deserializer(cls._infer_class_models()) - deserializer.key_extractors = ( # type: ignore - [ # type: ignore - attribute_key_case_insensitive_extractor, - rest_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - if key_extractors is None - else key_extractors - ) - return deserializer(cls.__name__, data, content_type=content_type) # type: ignore - - @classmethod - def _flatten_subtype(cls, key, objects): - if "_subtype_map" not in cls.__dict__: - return {} - result = dict(cls._subtype_map[key]) - for valuetype in cls._subtype_map[key].values(): - result.update(objects[valuetype]._flatten_subtype(key, objects)) - return result - - @classmethod - def _classify(cls, response, objects): - """Check the class _subtype_map for any child classes. - We want to ignore any inherited _subtype_maps. - Remove the polymorphic key from the initial data. - """ - for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): - subtype_value = None - - if not isinstance(response, ET.Element): - rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] - subtype_value = response.pop(rest_api_response_key, None) or response.pop(subtype_key, None) - else: - subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) - if subtype_value: - # Try to match base class. Can be class name only - # (bug to fix in Autorest to support x-ms-discriminator-name) - if cls.__name__ == subtype_value: - return cls - flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) - try: - return objects[flatten_mapping_type[subtype_value]] # type: ignore - except KeyError: - _LOGGER.warning( - "Subtype value %s has no mapping, use base class %s.", - subtype_value, - cls.__name__, - ) - break - else: - _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) - break - return cls - - @classmethod - def _get_rest_key_parts(cls, attr_key): - """Get the RestAPI key of this attr, split it and decode part - :param str attr_key: Attribute key must be in attribute_map. - :returns: A list of RestAPI part - :rtype: list - """ - rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) - return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] - - -def _decode_attribute_map_key(key): - """This decode a key in an _attribute_map to the actual key we want to look at - inside the received data. - - :param str key: A key string from the generated code - """ - return key.replace("\\.", ".") - - -class Serializer(object): - """Request object model serializer.""" - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} - days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} - months = { - 1: "Jan", - 2: "Feb", - 3: "Mar", - 4: "Apr", - 5: "May", - 6: "Jun", - 7: "Jul", - 8: "Aug", - 9: "Sep", - 10: "Oct", - 11: "Nov", - 12: "Dec", - } - validation = { - "min_length": lambda x, y: len(x) < y, - "max_length": lambda x, y: len(x) > y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes: Optional[Mapping[str, type]] = None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies: Dict[str, type] = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) # type: ignore - continue - if xml_desc.get("text", False): - serialized.text = new_attr # type: ignore - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) # type: ignore - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) # type: ignore - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = str(new_attr) - serialized.append(local_node) # type: ignore - else: # JSON - for k in reversed(keys): # type: ignore - new_attr = {k: new_attr} - - _new_attr = new_attr - _serialized = serialized - for k in keys: # type: ignore - if k not in _serialized: - _serialized.update(_new_attr) # type: ignore - _new_attr = _new_attr[k] # type: ignore - _serialized = _serialized[k] - except ValueError as err: - if isinstance(err, SerializationError): - raise - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise SerializationError(msg) from err - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type_str = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type_str, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ # type: ignore - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise SerializationError("Unable to build a model: " + str(err)) from err - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - output = output.replace("{", quote("{")).replace("}", quote("}")) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :keyword bool skip_quote: Whether to skip quote the serialized result. - Defaults to False. - :rtype: str, list - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # Treat the list aside, since we don't want to encode the div separator - if data_type.startswith("["): - internal_data_type = data_type[1:-1] - do_quote = not kwargs.get("skip_quote", False) - return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data is CoreNull: - return None - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise SerializationError(msg.format(data, data_type)) from err - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) # nosec - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): # type: ignore - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :keyword bool do_quote: Whether to quote the serialized result of each iterable element. - Defaults to False. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError as err: - if isinstance(err, SerializationError): - raise - serialized.append(None) - - if kwargs.get("do_quote", False): - serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError as err: - if isinstance(err, SerializationError): - raise - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) # type: ignore - return result - except ValueError: - for enum_value in enum_obj: # type: ignore - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_time(attr) - t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) - if attr.microsecond: - t += ".{:02}".format(attr.microsecond) - return t - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - if utc.tm_year > 9999 or utc.tm_year < 1: - raise OverflowError("Hit max or min date") - - microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") - if microseconds: - microseconds = "." + microseconds - date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( - utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec - ) - return date + microseconds + "Z" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise SerializationError(msg) from err - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise TypeError(msg) from err - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - dict_keys = cast(List[str], _FLATTEN.split(key)) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") - - def __init__(self, classes: Optional[Mapping[str, type]] = None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies: Dict[str, type] = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, str): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None or data is CoreNull: - return data - try: - attributes = response._attribute_map # type: ignore - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name # type: ignore - raise DeserializationError(msg) from err - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deserialize. - """ - if target is None: - return None, None - - if isinstance(target, str): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) # type: ignore - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ # type: ignore - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deserialize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.debug( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise DeserializationError(msg) from err - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, str): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, str): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) # nosec - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): # type: ignore - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) # type: ignore - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore - attr = attr + padding # type: ignore - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(str(attr)) # type: ignore - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise DeserializationError(msg) from err - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) # type: ignore - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise DeserializationError(msg) from err - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=0, defaultday=0) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - parsed_date = email.utils.parsedate_tz(attr) # type: ignore - date_obj = datetime.datetime( - *parsed_date[:6], tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise DeserializationError(msg) from err - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() # type: ignore - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise DeserializationError(msg) from err - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) # type: ignore - try: - attr = int(attr) - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise DeserializationError(msg) from err - else: - return date_obj +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + +# pylint: skip-file +# pyright: reportUnnecessaryTypeIgnoreComment=false + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs +from typing import ( + Dict, + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + TypeVar, + MutableMapping, + Type, + List, + Mapping, +) + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote +import xml.etree.ElementTree as ET + +import isodate # type: ignore + +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +ModelType = TypeVar("ModelType", bound="Model") +JSON = MutableMapping[str, Any] + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError as err: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise DeserializationError("XML is invalid") from err + elif content_type.startswith("text/"): + return data_as_str + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + + +class UTC(datetime.tzinfo): + """Time Zone info for handling UTC""" + + def utcoffset(self, dt): + """UTF offset for UTC is 0.""" + return datetime.timedelta(0) + + def tzname(self, dt): + """Timestamp representation.""" + return "Z" + + def dst(self, dt): + """No daylight saving for UTC.""" + return datetime.timedelta(hours=1) + + +try: + from datetime import timezone as _FixedOffset # type: ignore +except ImportError: # Python 2.7 + + class _FixedOffset(datetime.tzinfo): # type: ignore + """Fixed offset in minutes east from UTC. + Copy/pasted from Python doc + :param datetime.timedelta offset: offset in timedelta format + """ + + def __init__(self, offset): + self.__offset = offset + + def utcoffset(self, dt): + return self.__offset + + def tzname(self, dt): + return str(self.__offset.total_seconds() / 3600) + + def __repr__(self): + return "".format(self.tzname(None)) + + def dst(self, dt): + return datetime.timedelta(0) + + def __getinitargs__(self): + return (self.__offset,) + + +try: + from datetime import timezone + + TZ_UTC = timezone.utc +except ImportError: + TZ_UTC = UTC() # type: ignore + +_FLATTEN = re.compile(r"(? None: + self.additional_properties: Optional[Dict[str, Any]] = {} + for k in kwargs: + if k not in self._attribute_map: + _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) + elif k in self._validation and self._validation[k].get("readonly", False): + _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) + else: + setattr(self, k, kwargs[k]) + + def __eq__(self, other: Any) -> bool: + """Compare objects by comparing all attributes.""" + if isinstance(other, self.__class__): + return self.__dict__ == other.__dict__ + return False + + def __ne__(self, other: Any) -> bool: + """Compare objects by comparing all attributes.""" + return not self.__eq__(other) + + def __str__(self) -> str: + return str(self.__dict__) + + @classmethod + def enable_additional_properties_sending(cls) -> None: + cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} + + @classmethod + def is_xml_model(cls) -> bool: + try: + cls._xml_map # type: ignore + except AttributeError: + return False + return True + + @classmethod + def _create_xml_node(cls): + """Create XML node.""" + try: + xml_map = cls._xml_map # type: ignore + except AttributeError: + xml_map = {} + + return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) + + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Return the JSON that would be sent to server from this model. + + This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) # type: ignore + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, Dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. + + Advanced usage might optionally use a callback as parameter: + + .. code::python + + def my_key_transformer(key, attr_desc, value): + return key + + Key is the attribute name used in Python. Attr_desc + is a dict of metadata. Currently contains 'type' with the + msrest type and 'key' with the RestAPI encoded key. + Value is the current value in this object. + + The string returned will be used to serialize the key. + If the return type is a list, this is considered hierarchical + result dict. + + See the three examples in this file: + + - attribute_transformer + - full_restapi_key_transformer + - last_restapi_key_transformer + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param function key_transformer: A key transformer function. + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs) # type: ignore + + @classmethod + def _infer_class_models(cls): + try: + str_models = cls.__module__.rsplit(".", 1)[0] + models = sys.modules[str_models] + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + if cls.__name__ not in client_models: + raise ValueError("Not Autorest generated code") + except Exception: + # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. + client_models = {cls.__name__: cls} + return client_models + + @classmethod + def deserialize(cls: Type[ModelType], data: Any, content_type: Optional[str] = None) -> ModelType: + """Parse a str using the RestAPI syntax and return a model. + + :param str data: A str using RestAPI structure. JSON by default. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises: DeserializationError if something went wrong + """ + deserializer = Deserializer(cls._infer_class_models()) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def from_dict( + cls: Type[ModelType], + data: Any, + key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> ModelType: + """Parse a dict using given key extractor return a model. + + By default consider key + extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor + and last_rest_key_case_insensitive_extractor) + + :param dict data: A dict using RestAPI structure + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises: DeserializationError if something went wrong + """ + deserializer = Deserializer(cls._infer_class_models()) + deserializer.key_extractors = ( # type: ignore + [ # type: ignore + attribute_key_case_insensitive_extractor, + rest_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + if key_extractors is None + else key_extractors + ) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def _flatten_subtype(cls, key, objects): + if "_subtype_map" not in cls.__dict__: + return {} + result = dict(cls._subtype_map[key]) + for valuetype in cls._subtype_map[key].values(): + result.update(objects[valuetype]._flatten_subtype(key, objects)) + return result + + @classmethod + def _classify(cls, response, objects): + """Check the class _subtype_map for any child classes. + We want to ignore any inherited _subtype_maps. + Remove the polymorphic key from the initial data. + """ + for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): + subtype_value = None + + if not isinstance(response, ET.Element): + rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] + subtype_value = response.pop(rest_api_response_key, None) or response.pop(subtype_key, None) + else: + subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) + if subtype_value: + # Try to match base class. Can be class name only + # (bug to fix in Autorest to support x-ms-discriminator-name) + if cls.__name__ == subtype_value: + return cls + flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) + try: + return objects[flatten_mapping_type[subtype_value]] # type: ignore + except KeyError: + _LOGGER.warning( + "Subtype value %s has no mapping, use base class %s.", + subtype_value, + cls.__name__, + ) + break + else: + _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) + break + return cls + + @classmethod + def _get_rest_key_parts(cls, attr_key): + """Get the RestAPI key of this attr, split it and decode part + :param str attr_key: Attribute key must be in attribute_map. + :returns: A list of RestAPI part + :rtype: list + """ + rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) + return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] + + +def _decode_attribute_map_key(key): + """This decode a key in an _attribute_map to the actual key we want to look at + inside the received data. + + :param str key: A key string from the generated code + """ + return key.replace("\\.", ".") + + +class Serializer(object): + """Request object model serializer.""" + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} + days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} + months = { + 1: "Jan", + 2: "Feb", + 3: "Mar", + 4: "Apr", + 5: "May", + 6: "Jun", + 7: "Jul", + 8: "Aug", + 9: "Sep", + 10: "Oct", + 11: "Nov", + 12: "Dec", + } + validation = { + "min_length": lambda x, y: len(x) < y, + "max_length": lambda x, y: len(x) > y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0, + } + + def __init__(self, classes: Optional[Mapping[str, type]] = None): + self.serialize_type = { + "iso-8601": Serializer.serialize_iso, + "rfc-1123": Serializer.serialize_rfc, + "unix-time": Serializer.serialize_unix, + "duration": Serializer.serialize_duration, + "date": Serializer.serialize_date, + "time": Serializer.serialize_time, + "decimal": Serializer.serialize_decimal, + "long": Serializer.serialize_long, + "bytearray": Serializer.serialize_bytearray, + "base64": Serializer.serialize_base64, + "object": self.serialize_object, + "[]": self.serialize_iter, + "{}": self.serialize_dict, + } + self.dependencies: Dict[str, type] = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize(self, target_obj, data_type=None, **kwargs): + """Serialize data into a string according to type. + + :param target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises: SerializationError if serialization fails. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data(target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data(target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() + try: + attributes = target_obj._attribute_map + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == "": + if target_obj.additional_properties is not None: + serialized.update(target_obj.additional_properties) + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) + + if is_xml_model_serialization: + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + xml_prefix = xml_desc.get("prefix", None) + xml_ns = xml_desc.get("ns", None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) # type: ignore + continue + if xml_desc.get("text", False): + serialized.text = new_attr # type: ignore + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) # type: ignore + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) # type: ignore + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = str(new_attr) + serialized.append(local_node) # type: ignore + else: # JSON + for k in reversed(keys): # type: ignore + new_attr = {k: new_attr} + + _new_attr = new_attr + _serialized = serialized + for k in keys: # type: ignore + if k not in _serialized: + _serialized.update(_new_attr) # type: ignore + _new_attr = _new_attr[k] # type: ignore + _serialized = _serialized[k] + except ValueError as err: + if isinstance(err, SerializationError): + raise + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise SerializationError(msg) from err + else: + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises: SerializationError if serialization fails. + :raises: ValueError if data is None + """ + + # Just in case this is a dict + internal_data_type_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ # type: ignore + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) + except DeserializationError as err: + raise SerializationError("Unable to build a model: " + str(err)) from err + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + output = output.replace("{", quote("{")).replace("}", quote("}")) + else: + output = quote(str(output), safe="") + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :keyword bool skip_quote: Whether to skip quote the serialized result. + Defaults to False. + :rtype: str, list + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :param bool required: Whether it's essential that the data not be + empty or None + :raises: AttributeError if required data is None. + :raises: ValueError if data is None + :raises: SerializationError if serialization fails. + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data is CoreNull: + return None + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + elif data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, data.__class__) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise SerializationError(msg.format(data, data_type)) from err + else: + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param data: Object to be serialized. + :param str data_type: Type of object in the iterable. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + return eval(data_type)(data) # nosec + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param data: Object to be serialized. + :rtype: str + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): # type: ignore + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + else: + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list attr: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param bool required: Whether the objects in the iterable must + not be None or empty. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + :keyword bool do_quote: Whether to quote the serialized result of each iterable element. + Defaults to False. + :rtype: list, str + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized.append(None) + + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :param bool required: Whether the objects in the dictionary must + not be None or empty. + :rtype: dict + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) + if obj_type is _long_type: + return self.serialize_long(attr) + if obj_type is str: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + elif obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) # type: ignore + return result + except ValueError: + for enum_value in enum_obj: # type: ignore + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) + + @staticmethod + def serialize_bytearray(attr, **kwargs): + """Serialize bytearray into base-64 string. + + :param attr: Object to be serialized. + :rtype: str + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): + """Serialize str into base-64 string. + + :param attr: Object to be serialized. + :rtype: str + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): + """Serialize Decimal object to float. + + :param attr: Object to be serialized. + :rtype: float + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): + """Serialize long (Py2) or int (Py3). + + :param attr: Object to be serialized. + :rtype: int/long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def serialize_rfc(attr, **kwargs): + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises: TypeError if format invalid. + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError: + raise TypeError("RFC1123 object must be valid Datetime object.") + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises: SerializationError if format invalid. + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise SerializationError(msg) from err + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise TypeError(msg) from err + + @staticmethod + def serialize_unix(attr, **kwargs): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises: SerializationError if format invalid + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError: + raise TypeError("Unix time object must be valid Datetime object.") + + +def rest_key_extractor(attr, attr_desc, data): + key = attr_desc["key"] + working_data = data + + while "." in key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(List[str], _FLATTEN.split(key)) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + return working_data.get(key) + + +def rest_key_case_insensitive_extractor(attr, attr_desc, data): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + + +def last_rest_key_extractor(attr, attr_desc, data): + """Extract the attribute in "data" based on the last part of the JSON path key.""" + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + xml_name = internal_type_xml_map.get("name", internal_type.__name__) + xml_ns = internal_type_xml_map.get("ns", None) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + + # Look for a children + is_iter_type = attr_desc["type"].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # Integrate namespace if necessary + xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and "name" in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + else: + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + else: # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + ) + ) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + + +class Deserializer(object): + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + + def __init__(self, classes: Optional[Mapping[str, type]] = None): + self.deserialize_type = { + "iso-8601": Deserializer.deserialize_iso, + "rfc-1123": Deserializer.deserialize_rfc, + "unix-time": Deserializer.deserialize_unix, + "duration": Deserializer.deserialize_duration, + "date": Deserializer.deserialize_date, + "time": Deserializer.deserialize_time, + "decimal": Deserializer.deserialize_decimal, + "long": Deserializer.deserialize_long, + "bytearray": Deserializer.deserialize_bytearray, + "base64": Deserializer.deserialize_base64, + "object": self.deserialize_object, + "[]": self.deserialize_iter, + "{}": self.deserialize_dict, + } + self.deserialize_expected_types = { + "duration": (isodate.Duration, datetime.timedelta), + "iso-8601": (datetime.datetime), + } + self.dependencies: Dict[str, type] = dict(classes) if classes else {} + self.key_extractors = [rest_key_extractor, xml_key_extractor] + # Additional properties only works if the "rest_key_extractor" is used to + # extract the keys. Making it to work whatever the key extractor is too much + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] + try: + for attr, mapconfig in data._attribute_map.items(): + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig["type"] + internal_data_type = local_type.strip("[]{}") + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr(data, attr, self._deserialize(local_type, value)) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, str): + return self.deserialize_data(data, response) + elif isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None or data is CoreNull: + return data + try: + attributes = response._attribute_map # type: ignore + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name # type: ignore + raise DeserializationError(msg) from err + else: + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + """ + if target is None: + return None, None + + if isinstance(target, str): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) # type: ignore + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ # type: ignore + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + a deserialization error. + + :param str target_obj: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :param str content_type: Swagger "produces" if available. + """ + try: + return self(target_obj, data, content_type=content_type) + except: + _LOGGER.debug( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param raw_data: Data to be processed. + :param content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + # Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) + + # Assume this enough to recognize requests.Response without importing it. + if hasattr(raw_data, "_content_consumed"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) + + if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param response: The response model class. + :param d_attrs: The deserialized response attributes. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [k for k, v in response._validation.items() if v.get("readonly")] + const = [k for k, v in response._validation.items() if v.get("constant")] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore + raise DeserializationError(msg + str(err)) + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) + + def deserialize_data(self, data, data_type): + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise DeserializationError(msg) from err + else: + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :rtype: dict + :raises: TypeError if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, str): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + else: + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :rtype: str, int, float or bool + :raises: TypeError if string format is not valid. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + else: + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + elif isinstance(attr, str): + if attr.lower() in ["true", "1"]: + return True + elif attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + return eval(data_type)(attr) # nosec + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): # type: ignore + return data + except NameError: + return str(data) + else: + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + data = data.value + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + try: + return list(enum_obj.__members__.values())[data] + except IndexError: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :rtype: bytearray + :raises: TypeError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) # type: ignore + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :rtype: bytearray + :raises: TypeError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :rtype: Decimal + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(str(attr)) # type: ignore + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise DeserializationError(msg) from err + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :rtype: long or int + :raises: ValueError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) # type: ignore + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :rtype: TimeDelta + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + else: + return duration + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :rtype: Date + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + return isodate.parse_date(attr, defaultmonth=0, defaultday=0) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: Datetime + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) # type: ignore + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise DeserializationError(msg) from err + else: + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: Datetime + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() # type: ignore + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise DeserializationError(msg) from err + else: + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :rtype: Datetime + :raises: DeserializationError if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) # type: ignore + try: + attr = int(attr) + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise DeserializationError(msg) from err + else: + return date_obj diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/_version.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/_version.py index 497563b85b8..a712687790e 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/_version.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/_version.py @@ -1,9 +1,9 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.7.0" +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "0.7.0" diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/__init__.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/__init__.py index 4fed606c498..0ec156d96fb 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/__init__.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/__init__.py @@ -1,23 +1,23 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._cosmos_db_management_client import CosmosDBManagementClient - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "CosmosDBManagementClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._cosmos_db_management_client import CosmosDBManagementClient + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "CosmosDBManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/_configuration.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/_configuration.py index a6bf18b87de..42b70bdac41 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/_configuration.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/_configuration.py @@ -1,65 +1,65 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, TYPE_CHECKING - -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy - -from .._version import VERSION - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core.credentials_async import AsyncTokenCredential - - -class CosmosDBManagementClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long - """Configuration for CosmosDBManagementClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str - :keyword api_version: Api Version. Default value is "2024-09-01-preview". Note that overriding - this default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "2024-09-01-preview") - - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - if subscription_id is None: - raise ValueError("Parameter 'subscription_id' must not be None.") - - self.credential = credential - self.subscription_id = subscription_id - self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) - kwargs.setdefault("sdk_moniker", "mgmt-cosmosdb/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - if self.credential and not self.authentication_policy: - self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( - self.credential, *self.credential_scopes, **kwargs - ) +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING + +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class CosmosDBManagementClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long + """Configuration for CosmosDBManagementClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2024-09-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + api_version: str = kwargs.pop("api_version", "2024-09-01-preview") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-cosmosdb/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/_cosmos_db_management_client.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/_cosmos_db_management_client.py index 6d63be0d4ca..99bbf2ad941 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/_cosmos_db_management_client.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/_cosmos_db_management_client.py @@ -1,383 +1,383 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING -from typing_extensions import Self - -from azure.core.pipeline import policies -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.mgmt.core import AsyncARMPipelineClient -from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy - -from .. import models as _models -from .._serialization import Deserializer, Serializer -from ._configuration import CosmosDBManagementClientConfiguration -from .operations import ( - CassandraClustersOperations, - CassandraDataCentersOperations, - CassandraResourcesOperations, - ChaosFaultOperations, - CollectionOperations, - CollectionPartitionOperations, - CollectionPartitionRegionOperations, - CollectionRegionOperations, - DataTransferJobsOperations, - DatabaseAccountRegionOperations, - DatabaseAccountsOperations, - DatabaseOperations, - GraphResourcesOperations, - GremlinResourcesOperations, - LocationsOperations, - MongoDBResourcesOperations, - NetworkSecurityPerimeterConfigurationsOperations, - NotebookWorkspacesOperations, - Operations, - PartitionKeyRangeIdOperations, - PartitionKeyRangeIdRegionOperations, - PercentileOperations, - PercentileSourceTargetOperations, - PercentileTargetOperations, - PrivateEndpointConnectionsOperations, - PrivateLinkResourcesOperations, - RestorableDatabaseAccountsOperations, - RestorableGremlinDatabasesOperations, - RestorableGremlinGraphsOperations, - RestorableGremlinResourcesOperations, - RestorableMongodbCollectionsOperations, - RestorableMongodbDatabasesOperations, - RestorableMongodbResourcesOperations, - RestorableSqlContainersOperations, - RestorableSqlDatabasesOperations, - RestorableSqlResourcesOperations, - RestorableTableResourcesOperations, - RestorableTablesOperations, - ServiceOperations, - SqlResourcesOperations, - TableResourcesOperations, - ThroughputPoolAccountOperations, - ThroughputPoolAccountsOperations, - ThroughputPoolOperations, - ThroughputPoolsOperations, -) - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core.credentials_async import AsyncTokenCredential - - -class CosmosDBManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes - """Azure Cosmos DB Database Service Resource Provider REST API. - - :ivar database_accounts: DatabaseAccountsOperations operations - :vartype database_accounts: azure.mgmt.cosmosdb.aio.operations.DatabaseAccountsOperations - :ivar operations: Operations operations - :vartype operations: azure.mgmt.cosmosdb.aio.operations.Operations - :ivar database: DatabaseOperations operations - :vartype database: azure.mgmt.cosmosdb.aio.operations.DatabaseOperations - :ivar collection: CollectionOperations operations - :vartype collection: azure.mgmt.cosmosdb.aio.operations.CollectionOperations - :ivar collection_region: CollectionRegionOperations operations - :vartype collection_region: azure.mgmt.cosmosdb.aio.operations.CollectionRegionOperations - :ivar database_account_region: DatabaseAccountRegionOperations operations - :vartype database_account_region: - azure.mgmt.cosmosdb.aio.operations.DatabaseAccountRegionOperations - :ivar percentile_source_target: PercentileSourceTargetOperations operations - :vartype percentile_source_target: - azure.mgmt.cosmosdb.aio.operations.PercentileSourceTargetOperations - :ivar percentile_target: PercentileTargetOperations operations - :vartype percentile_target: azure.mgmt.cosmosdb.aio.operations.PercentileTargetOperations - :ivar percentile: PercentileOperations operations - :vartype percentile: azure.mgmt.cosmosdb.aio.operations.PercentileOperations - :ivar collection_partition_region: CollectionPartitionRegionOperations operations - :vartype collection_partition_region: - azure.mgmt.cosmosdb.aio.operations.CollectionPartitionRegionOperations - :ivar collection_partition: CollectionPartitionOperations operations - :vartype collection_partition: azure.mgmt.cosmosdb.aio.operations.CollectionPartitionOperations - :ivar partition_key_range_id: PartitionKeyRangeIdOperations operations - :vartype partition_key_range_id: - azure.mgmt.cosmosdb.aio.operations.PartitionKeyRangeIdOperations - :ivar partition_key_range_id_region: PartitionKeyRangeIdRegionOperations operations - :vartype partition_key_range_id_region: - azure.mgmt.cosmosdb.aio.operations.PartitionKeyRangeIdRegionOperations - :ivar graph_resources: GraphResourcesOperations operations - :vartype graph_resources: azure.mgmt.cosmosdb.aio.operations.GraphResourcesOperations - :ivar sql_resources: SqlResourcesOperations operations - :vartype sql_resources: azure.mgmt.cosmosdb.aio.operations.SqlResourcesOperations - :ivar mongo_db_resources: MongoDBResourcesOperations operations - :vartype mongo_db_resources: azure.mgmt.cosmosdb.aio.operations.MongoDBResourcesOperations - :ivar table_resources: TableResourcesOperations operations - :vartype table_resources: azure.mgmt.cosmosdb.aio.operations.TableResourcesOperations - :ivar cassandra_resources: CassandraResourcesOperations operations - :vartype cassandra_resources: azure.mgmt.cosmosdb.aio.operations.CassandraResourcesOperations - :ivar gremlin_resources: GremlinResourcesOperations operations - :vartype gremlin_resources: azure.mgmt.cosmosdb.aio.operations.GremlinResourcesOperations - :ivar locations: LocationsOperations operations - :vartype locations: azure.mgmt.cosmosdb.aio.operations.LocationsOperations - :ivar data_transfer_jobs: DataTransferJobsOperations operations - :vartype data_transfer_jobs: azure.mgmt.cosmosdb.aio.operations.DataTransferJobsOperations - :ivar cassandra_clusters: CassandraClustersOperations operations - :vartype cassandra_clusters: azure.mgmt.cosmosdb.aio.operations.CassandraClustersOperations - :ivar cassandra_data_centers: CassandraDataCentersOperations operations - :vartype cassandra_data_centers: - azure.mgmt.cosmosdb.aio.operations.CassandraDataCentersOperations - :ivar network_security_perimeter_configurations: - NetworkSecurityPerimeterConfigurationsOperations operations - :vartype network_security_perimeter_configurations: - azure.mgmt.cosmosdb.aio.operations.NetworkSecurityPerimeterConfigurationsOperations - :ivar notebook_workspaces: NotebookWorkspacesOperations operations - :vartype notebook_workspaces: azure.mgmt.cosmosdb.aio.operations.NotebookWorkspacesOperations - :ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations - :vartype private_endpoint_connections: - azure.mgmt.cosmosdb.aio.operations.PrivateEndpointConnectionsOperations - :ivar private_link_resources: PrivateLinkResourcesOperations operations - :vartype private_link_resources: - azure.mgmt.cosmosdb.aio.operations.PrivateLinkResourcesOperations - :ivar restorable_database_accounts: RestorableDatabaseAccountsOperations operations - :vartype restorable_database_accounts: - azure.mgmt.cosmosdb.aio.operations.RestorableDatabaseAccountsOperations - :ivar restorable_sql_databases: RestorableSqlDatabasesOperations operations - :vartype restorable_sql_databases: - azure.mgmt.cosmosdb.aio.operations.RestorableSqlDatabasesOperations - :ivar restorable_sql_containers: RestorableSqlContainersOperations operations - :vartype restorable_sql_containers: - azure.mgmt.cosmosdb.aio.operations.RestorableSqlContainersOperations - :ivar restorable_sql_resources: RestorableSqlResourcesOperations operations - :vartype restorable_sql_resources: - azure.mgmt.cosmosdb.aio.operations.RestorableSqlResourcesOperations - :ivar restorable_mongodb_databases: RestorableMongodbDatabasesOperations operations - :vartype restorable_mongodb_databases: - azure.mgmt.cosmosdb.aio.operations.RestorableMongodbDatabasesOperations - :ivar restorable_mongodb_collections: RestorableMongodbCollectionsOperations operations - :vartype restorable_mongodb_collections: - azure.mgmt.cosmosdb.aio.operations.RestorableMongodbCollectionsOperations - :ivar restorable_mongodb_resources: RestorableMongodbResourcesOperations operations - :vartype restorable_mongodb_resources: - azure.mgmt.cosmosdb.aio.operations.RestorableMongodbResourcesOperations - :ivar restorable_gremlin_databases: RestorableGremlinDatabasesOperations operations - :vartype restorable_gremlin_databases: - azure.mgmt.cosmosdb.aio.operations.RestorableGremlinDatabasesOperations - :ivar restorable_gremlin_graphs: RestorableGremlinGraphsOperations operations - :vartype restorable_gremlin_graphs: - azure.mgmt.cosmosdb.aio.operations.RestorableGremlinGraphsOperations - :ivar restorable_gremlin_resources: RestorableGremlinResourcesOperations operations - :vartype restorable_gremlin_resources: - azure.mgmt.cosmosdb.aio.operations.RestorableGremlinResourcesOperations - :ivar restorable_tables: RestorableTablesOperations operations - :vartype restorable_tables: azure.mgmt.cosmosdb.aio.operations.RestorableTablesOperations - :ivar restorable_table_resources: RestorableTableResourcesOperations operations - :vartype restorable_table_resources: - azure.mgmt.cosmosdb.aio.operations.RestorableTableResourcesOperations - :ivar service: ServiceOperations operations - :vartype service: azure.mgmt.cosmosdb.aio.operations.ServiceOperations - :ivar throughput_pools: ThroughputPoolsOperations operations - :vartype throughput_pools: azure.mgmt.cosmosdb.aio.operations.ThroughputPoolsOperations - :ivar throughput_pool: ThroughputPoolOperations operations - :vartype throughput_pool: azure.mgmt.cosmosdb.aio.operations.ThroughputPoolOperations - :ivar throughput_pool_accounts: ThroughputPoolAccountsOperations operations - :vartype throughput_pool_accounts: - azure.mgmt.cosmosdb.aio.operations.ThroughputPoolAccountsOperations - :ivar throughput_pool_account: ThroughputPoolAccountOperations operations - :vartype throughput_pool_account: - azure.mgmt.cosmosdb.aio.operations.ThroughputPoolAccountOperations - :ivar chaos_fault: ChaosFaultOperations operations - :vartype chaos_fault: azure.mgmt.cosmosdb.aio.operations.ChaosFaultOperations - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str - :param base_url: Service URL. Default value is "https://management.azure.com". - :type base_url: str - :keyword api_version: Api Version. Default value is "2024-09-01-preview". Note that overriding - this default value may result in unsupported behavior. - :paramtype api_version: str - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - """ - - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - base_url: str = "https://management.azure.com", - **kwargs: Any - ) -> None: - self._config = CosmosDBManagementClientConfiguration( - credential=credential, subscription_id=subscription_id, **kwargs - ) - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - AsyncARMAutoResourceProviderRegistrationPolicy(), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, policies=_policies, **kwargs) - - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) - self._serialize.client_side_validation = False - self.database_accounts = DatabaseAccountsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) - self.database = DatabaseOperations(self._client, self._config, self._serialize, self._deserialize) - self.collection = CollectionOperations(self._client, self._config, self._serialize, self._deserialize) - self.collection_region = CollectionRegionOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.database_account_region = DatabaseAccountRegionOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.percentile_source_target = PercentileSourceTargetOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.percentile_target = PercentileTargetOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.percentile = PercentileOperations(self._client, self._config, self._serialize, self._deserialize) - self.collection_partition_region = CollectionPartitionRegionOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.collection_partition = CollectionPartitionOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.partition_key_range_id = PartitionKeyRangeIdOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.partition_key_range_id_region = PartitionKeyRangeIdRegionOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.graph_resources = GraphResourcesOperations(self._client, self._config, self._serialize, self._deserialize) - self.sql_resources = SqlResourcesOperations(self._client, self._config, self._serialize, self._deserialize) - self.mongo_db_resources = MongoDBResourcesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.table_resources = TableResourcesOperations(self._client, self._config, self._serialize, self._deserialize) - self.cassandra_resources = CassandraResourcesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.gremlin_resources = GremlinResourcesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.locations = LocationsOperations(self._client, self._config, self._serialize, self._deserialize) - self.data_transfer_jobs = DataTransferJobsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.cassandra_clusters = CassandraClustersOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.cassandra_data_centers = CassandraDataCentersOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.network_security_perimeter_configurations = NetworkSecurityPerimeterConfigurationsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.notebook_workspaces = NotebookWorkspacesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.private_endpoint_connections = PrivateEndpointConnectionsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.private_link_resources = PrivateLinkResourcesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.restorable_database_accounts = RestorableDatabaseAccountsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.restorable_sql_databases = RestorableSqlDatabasesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.restorable_sql_containers = RestorableSqlContainersOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.restorable_sql_resources = RestorableSqlResourcesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.restorable_mongodb_databases = RestorableMongodbDatabasesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.restorable_mongodb_collections = RestorableMongodbCollectionsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.restorable_mongodb_resources = RestorableMongodbResourcesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.restorable_gremlin_databases = RestorableGremlinDatabasesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.restorable_gremlin_graphs = RestorableGremlinGraphsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.restorable_gremlin_resources = RestorableGremlinResourcesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.restorable_tables = RestorableTablesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.restorable_table_resources = RestorableTableResourcesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.service = ServiceOperations(self._client, self._config, self._serialize, self._deserialize) - self.throughput_pools = ThroughputPoolsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.throughput_pool = ThroughputPoolOperations(self._client, self._config, self._serialize, self._deserialize) - self.throughput_pool_accounts = ThroughputPoolAccountsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.throughput_pool_account = ThroughputPoolAccountOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.chaos_fault = ChaosFaultOperations(self._client, self._config, self._serialize, self._deserialize) - - def _send_request( - self, request: HttpRequest, *, stream: bool = False, **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = await client._send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> Self: - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details: Any) -> None: - await self._client.__aexit__(*exc_details) +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self + +from azure.core.pipeline import policies +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy + +from .. import models as _models +from .._serialization import Deserializer, Serializer +from ._configuration import CosmosDBManagementClientConfiguration +from .operations import ( + CassandraClustersOperations, + CassandraDataCentersOperations, + CassandraResourcesOperations, + ChaosFaultOperations, + CollectionOperations, + CollectionPartitionOperations, + CollectionPartitionRegionOperations, + CollectionRegionOperations, + DataTransferJobsOperations, + DatabaseAccountRegionOperations, + DatabaseAccountsOperations, + DatabaseOperations, + GraphResourcesOperations, + GremlinResourcesOperations, + LocationsOperations, + MongoDBResourcesOperations, + NetworkSecurityPerimeterConfigurationsOperations, + NotebookWorkspacesOperations, + Operations, + PartitionKeyRangeIdOperations, + PartitionKeyRangeIdRegionOperations, + PercentileOperations, + PercentileSourceTargetOperations, + PercentileTargetOperations, + PrivateEndpointConnectionsOperations, + PrivateLinkResourcesOperations, + RestorableDatabaseAccountsOperations, + RestorableGremlinDatabasesOperations, + RestorableGremlinGraphsOperations, + RestorableGremlinResourcesOperations, + RestorableMongodbCollectionsOperations, + RestorableMongodbDatabasesOperations, + RestorableMongodbResourcesOperations, + RestorableSqlContainersOperations, + RestorableSqlDatabasesOperations, + RestorableSqlResourcesOperations, + RestorableTableResourcesOperations, + RestorableTablesOperations, + ServiceOperations, + SqlResourcesOperations, + TableResourcesOperations, + ThroughputPoolAccountOperations, + ThroughputPoolAccountsOperations, + ThroughputPoolOperations, + ThroughputPoolsOperations, +) + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class CosmosDBManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes + """Azure Cosmos DB Database Service Resource Provider REST API. + + :ivar database_accounts: DatabaseAccountsOperations operations + :vartype database_accounts: azure.mgmt.cosmosdb.aio.operations.DatabaseAccountsOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.cosmosdb.aio.operations.Operations + :ivar database: DatabaseOperations operations + :vartype database: azure.mgmt.cosmosdb.aio.operations.DatabaseOperations + :ivar collection: CollectionOperations operations + :vartype collection: azure.mgmt.cosmosdb.aio.operations.CollectionOperations + :ivar collection_region: CollectionRegionOperations operations + :vartype collection_region: azure.mgmt.cosmosdb.aio.operations.CollectionRegionOperations + :ivar database_account_region: DatabaseAccountRegionOperations operations + :vartype database_account_region: + azure.mgmt.cosmosdb.aio.operations.DatabaseAccountRegionOperations + :ivar percentile_source_target: PercentileSourceTargetOperations operations + :vartype percentile_source_target: + azure.mgmt.cosmosdb.aio.operations.PercentileSourceTargetOperations + :ivar percentile_target: PercentileTargetOperations operations + :vartype percentile_target: azure.mgmt.cosmosdb.aio.operations.PercentileTargetOperations + :ivar percentile: PercentileOperations operations + :vartype percentile: azure.mgmt.cosmosdb.aio.operations.PercentileOperations + :ivar collection_partition_region: CollectionPartitionRegionOperations operations + :vartype collection_partition_region: + azure.mgmt.cosmosdb.aio.operations.CollectionPartitionRegionOperations + :ivar collection_partition: CollectionPartitionOperations operations + :vartype collection_partition: azure.mgmt.cosmosdb.aio.operations.CollectionPartitionOperations + :ivar partition_key_range_id: PartitionKeyRangeIdOperations operations + :vartype partition_key_range_id: + azure.mgmt.cosmosdb.aio.operations.PartitionKeyRangeIdOperations + :ivar partition_key_range_id_region: PartitionKeyRangeIdRegionOperations operations + :vartype partition_key_range_id_region: + azure.mgmt.cosmosdb.aio.operations.PartitionKeyRangeIdRegionOperations + :ivar graph_resources: GraphResourcesOperations operations + :vartype graph_resources: azure.mgmt.cosmosdb.aio.operations.GraphResourcesOperations + :ivar sql_resources: SqlResourcesOperations operations + :vartype sql_resources: azure.mgmt.cosmosdb.aio.operations.SqlResourcesOperations + :ivar mongo_db_resources: MongoDBResourcesOperations operations + :vartype mongo_db_resources: azure.mgmt.cosmosdb.aio.operations.MongoDBResourcesOperations + :ivar table_resources: TableResourcesOperations operations + :vartype table_resources: azure.mgmt.cosmosdb.aio.operations.TableResourcesOperations + :ivar cassandra_resources: CassandraResourcesOperations operations + :vartype cassandra_resources: azure.mgmt.cosmosdb.aio.operations.CassandraResourcesOperations + :ivar gremlin_resources: GremlinResourcesOperations operations + :vartype gremlin_resources: azure.mgmt.cosmosdb.aio.operations.GremlinResourcesOperations + :ivar locations: LocationsOperations operations + :vartype locations: azure.mgmt.cosmosdb.aio.operations.LocationsOperations + :ivar data_transfer_jobs: DataTransferJobsOperations operations + :vartype data_transfer_jobs: azure.mgmt.cosmosdb.aio.operations.DataTransferJobsOperations + :ivar cassandra_clusters: CassandraClustersOperations operations + :vartype cassandra_clusters: azure.mgmt.cosmosdb.aio.operations.CassandraClustersOperations + :ivar cassandra_data_centers: CassandraDataCentersOperations operations + :vartype cassandra_data_centers: + azure.mgmt.cosmosdb.aio.operations.CassandraDataCentersOperations + :ivar network_security_perimeter_configurations: + NetworkSecurityPerimeterConfigurationsOperations operations + :vartype network_security_perimeter_configurations: + azure.mgmt.cosmosdb.aio.operations.NetworkSecurityPerimeterConfigurationsOperations + :ivar notebook_workspaces: NotebookWorkspacesOperations operations + :vartype notebook_workspaces: azure.mgmt.cosmosdb.aio.operations.NotebookWorkspacesOperations + :ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations + :vartype private_endpoint_connections: + azure.mgmt.cosmosdb.aio.operations.PrivateEndpointConnectionsOperations + :ivar private_link_resources: PrivateLinkResourcesOperations operations + :vartype private_link_resources: + azure.mgmt.cosmosdb.aio.operations.PrivateLinkResourcesOperations + :ivar restorable_database_accounts: RestorableDatabaseAccountsOperations operations + :vartype restorable_database_accounts: + azure.mgmt.cosmosdb.aio.operations.RestorableDatabaseAccountsOperations + :ivar restorable_sql_databases: RestorableSqlDatabasesOperations operations + :vartype restorable_sql_databases: + azure.mgmt.cosmosdb.aio.operations.RestorableSqlDatabasesOperations + :ivar restorable_sql_containers: RestorableSqlContainersOperations operations + :vartype restorable_sql_containers: + azure.mgmt.cosmosdb.aio.operations.RestorableSqlContainersOperations + :ivar restorable_sql_resources: RestorableSqlResourcesOperations operations + :vartype restorable_sql_resources: + azure.mgmt.cosmosdb.aio.operations.RestorableSqlResourcesOperations + :ivar restorable_mongodb_databases: RestorableMongodbDatabasesOperations operations + :vartype restorable_mongodb_databases: + azure.mgmt.cosmosdb.aio.operations.RestorableMongodbDatabasesOperations + :ivar restorable_mongodb_collections: RestorableMongodbCollectionsOperations operations + :vartype restorable_mongodb_collections: + azure.mgmt.cosmosdb.aio.operations.RestorableMongodbCollectionsOperations + :ivar restorable_mongodb_resources: RestorableMongodbResourcesOperations operations + :vartype restorable_mongodb_resources: + azure.mgmt.cosmosdb.aio.operations.RestorableMongodbResourcesOperations + :ivar restorable_gremlin_databases: RestorableGremlinDatabasesOperations operations + :vartype restorable_gremlin_databases: + azure.mgmt.cosmosdb.aio.operations.RestorableGremlinDatabasesOperations + :ivar restorable_gremlin_graphs: RestorableGremlinGraphsOperations operations + :vartype restorable_gremlin_graphs: + azure.mgmt.cosmosdb.aio.operations.RestorableGremlinGraphsOperations + :ivar restorable_gremlin_resources: RestorableGremlinResourcesOperations operations + :vartype restorable_gremlin_resources: + azure.mgmt.cosmosdb.aio.operations.RestorableGremlinResourcesOperations + :ivar restorable_tables: RestorableTablesOperations operations + :vartype restorable_tables: azure.mgmt.cosmosdb.aio.operations.RestorableTablesOperations + :ivar restorable_table_resources: RestorableTableResourcesOperations operations + :vartype restorable_table_resources: + azure.mgmt.cosmosdb.aio.operations.RestorableTableResourcesOperations + :ivar service: ServiceOperations operations + :vartype service: azure.mgmt.cosmosdb.aio.operations.ServiceOperations + :ivar throughput_pools: ThroughputPoolsOperations operations + :vartype throughput_pools: azure.mgmt.cosmosdb.aio.operations.ThroughputPoolsOperations + :ivar throughput_pool: ThroughputPoolOperations operations + :vartype throughput_pool: azure.mgmt.cosmosdb.aio.operations.ThroughputPoolOperations + :ivar throughput_pool_accounts: ThroughputPoolAccountsOperations operations + :vartype throughput_pool_accounts: + azure.mgmt.cosmosdb.aio.operations.ThroughputPoolAccountsOperations + :ivar throughput_pool_account: ThroughputPoolAccountOperations operations + :vartype throughput_pool_account: + azure.mgmt.cosmosdb.aio.operations.ThroughputPoolAccountOperations + :ivar chaos_fault: ChaosFaultOperations operations + :vartype chaos_fault: azure.mgmt.cosmosdb.aio.operations.ChaosFaultOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2024-09-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = CosmosDBManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + AsyncARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, policies=_policies, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.database_accounts = DatabaseAccountsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.database = DatabaseOperations(self._client, self._config, self._serialize, self._deserialize) + self.collection = CollectionOperations(self._client, self._config, self._serialize, self._deserialize) + self.collection_region = CollectionRegionOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.database_account_region = DatabaseAccountRegionOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.percentile_source_target = PercentileSourceTargetOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.percentile_target = PercentileTargetOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.percentile = PercentileOperations(self._client, self._config, self._serialize, self._deserialize) + self.collection_partition_region = CollectionPartitionRegionOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.collection_partition = CollectionPartitionOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.partition_key_range_id = PartitionKeyRangeIdOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.partition_key_range_id_region = PartitionKeyRangeIdRegionOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.graph_resources = GraphResourcesOperations(self._client, self._config, self._serialize, self._deserialize) + self.sql_resources = SqlResourcesOperations(self._client, self._config, self._serialize, self._deserialize) + self.mongo_db_resources = MongoDBResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.table_resources = TableResourcesOperations(self._client, self._config, self._serialize, self._deserialize) + self.cassandra_resources = CassandraResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.gremlin_resources = GremlinResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.locations = LocationsOperations(self._client, self._config, self._serialize, self._deserialize) + self.data_transfer_jobs = DataTransferJobsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.cassandra_clusters = CassandraClustersOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.cassandra_data_centers = CassandraDataCentersOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.network_security_perimeter_configurations = NetworkSecurityPerimeterConfigurationsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.notebook_workspaces = NotebookWorkspacesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.private_endpoint_connections = PrivateEndpointConnectionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.private_link_resources = PrivateLinkResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.restorable_database_accounts = RestorableDatabaseAccountsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.restorable_sql_databases = RestorableSqlDatabasesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.restorable_sql_containers = RestorableSqlContainersOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.restorable_sql_resources = RestorableSqlResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.restorable_mongodb_databases = RestorableMongodbDatabasesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.restorable_mongodb_collections = RestorableMongodbCollectionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.restorable_mongodb_resources = RestorableMongodbResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.restorable_gremlin_databases = RestorableGremlinDatabasesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.restorable_gremlin_graphs = RestorableGremlinGraphsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.restorable_gremlin_resources = RestorableGremlinResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.restorable_tables = RestorableTablesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.restorable_table_resources = RestorableTableResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.service = ServiceOperations(self._client, self._config, self._serialize, self._deserialize) + self.throughput_pools = ThroughputPoolsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.throughput_pool = ThroughputPoolOperations(self._client, self._config, self._serialize, self._deserialize) + self.throughput_pool_accounts = ThroughputPoolAccountsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.throughput_pool_account = ThroughputPoolAccountOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.chaos_fault = ChaosFaultOperations(self._client, self._config, self._serialize, self._deserialize) + + def _send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> Self: + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/_patch.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/_patch.py index 04676c9e627..17dbc073e01 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/_patch.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/_patch.py @@ -1,32 +1,32 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - - -# This file is used for handwritten extensions to the generated code. Example: -# https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md -def patch_sdk(): - pass +# coding=utf-8 +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + + +# This file is used for handwritten extensions to the generated code. Example: +# https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md +def patch_sdk(): + pass diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/__init__.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/__init__.py index 317f6d4122d..a6aff077c84 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/__init__.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/__init__.py @@ -1,107 +1,107 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._database_accounts_operations import DatabaseAccountsOperations -from ._operations import Operations -from ._database_operations import DatabaseOperations -from ._collection_operations import CollectionOperations -from ._collection_region_operations import CollectionRegionOperations -from ._database_account_region_operations import DatabaseAccountRegionOperations -from ._percentile_source_target_operations import PercentileSourceTargetOperations -from ._percentile_target_operations import PercentileTargetOperations -from ._percentile_operations import PercentileOperations -from ._collection_partition_region_operations import CollectionPartitionRegionOperations -from ._collection_partition_operations import CollectionPartitionOperations -from ._partition_key_range_id_operations import PartitionKeyRangeIdOperations -from ._partition_key_range_id_region_operations import PartitionKeyRangeIdRegionOperations -from ._graph_resources_operations import GraphResourcesOperations -from ._sql_resources_operations import SqlResourcesOperations -from ._mongo_db_resources_operations import MongoDBResourcesOperations -from ._table_resources_operations import TableResourcesOperations -from ._cassandra_resources_operations import CassandraResourcesOperations -from ._gremlin_resources_operations import GremlinResourcesOperations -from ._locations_operations import LocationsOperations -from ._data_transfer_jobs_operations import DataTransferJobsOperations -from ._cassandra_clusters_operations import CassandraClustersOperations -from ._cassandra_data_centers_operations import CassandraDataCentersOperations -from ._network_security_perimeter_configurations_operations import NetworkSecurityPerimeterConfigurationsOperations -from ._notebook_workspaces_operations import NotebookWorkspacesOperations -from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations -from ._private_link_resources_operations import PrivateLinkResourcesOperations -from ._restorable_database_accounts_operations import RestorableDatabaseAccountsOperations -from ._restorable_sql_databases_operations import RestorableSqlDatabasesOperations -from ._restorable_sql_containers_operations import RestorableSqlContainersOperations -from ._restorable_sql_resources_operations import RestorableSqlResourcesOperations -from ._restorable_mongodb_databases_operations import RestorableMongodbDatabasesOperations -from ._restorable_mongodb_collections_operations import RestorableMongodbCollectionsOperations -from ._restorable_mongodb_resources_operations import RestorableMongodbResourcesOperations -from ._restorable_gremlin_databases_operations import RestorableGremlinDatabasesOperations -from ._restorable_gremlin_graphs_operations import RestorableGremlinGraphsOperations -from ._restorable_gremlin_resources_operations import RestorableGremlinResourcesOperations -from ._restorable_tables_operations import RestorableTablesOperations -from ._restorable_table_resources_operations import RestorableTableResourcesOperations -from ._service_operations import ServiceOperations -from ._throughput_pools_operations import ThroughputPoolsOperations -from ._throughput_pool_operations import ThroughputPoolOperations -from ._throughput_pool_accounts_operations import ThroughputPoolAccountsOperations -from ._throughput_pool_account_operations import ThroughputPoolAccountOperations -from ._chaos_fault_operations import ChaosFaultOperations - -from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "DatabaseAccountsOperations", - "Operations", - "DatabaseOperations", - "CollectionOperations", - "CollectionRegionOperations", - "DatabaseAccountRegionOperations", - "PercentileSourceTargetOperations", - "PercentileTargetOperations", - "PercentileOperations", - "CollectionPartitionRegionOperations", - "CollectionPartitionOperations", - "PartitionKeyRangeIdOperations", - "PartitionKeyRangeIdRegionOperations", - "GraphResourcesOperations", - "SqlResourcesOperations", - "MongoDBResourcesOperations", - "TableResourcesOperations", - "CassandraResourcesOperations", - "GremlinResourcesOperations", - "LocationsOperations", - "DataTransferJobsOperations", - "CassandraClustersOperations", - "CassandraDataCentersOperations", - "NetworkSecurityPerimeterConfigurationsOperations", - "NotebookWorkspacesOperations", - "PrivateEndpointConnectionsOperations", - "PrivateLinkResourcesOperations", - "RestorableDatabaseAccountsOperations", - "RestorableSqlDatabasesOperations", - "RestorableSqlContainersOperations", - "RestorableSqlResourcesOperations", - "RestorableMongodbDatabasesOperations", - "RestorableMongodbCollectionsOperations", - "RestorableMongodbResourcesOperations", - "RestorableGremlinDatabasesOperations", - "RestorableGremlinGraphsOperations", - "RestorableGremlinResourcesOperations", - "RestorableTablesOperations", - "RestorableTableResourcesOperations", - "ServiceOperations", - "ThroughputPoolsOperations", - "ThroughputPoolOperations", - "ThroughputPoolAccountsOperations", - "ThroughputPoolAccountOperations", - "ChaosFaultOperations", -] -__all__.extend([p for p in _patch_all if p not in __all__]) -_patch_sdk() +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._database_accounts_operations import DatabaseAccountsOperations +from ._operations import Operations +from ._database_operations import DatabaseOperations +from ._collection_operations import CollectionOperations +from ._collection_region_operations import CollectionRegionOperations +from ._database_account_region_operations import DatabaseAccountRegionOperations +from ._percentile_source_target_operations import PercentileSourceTargetOperations +from ._percentile_target_operations import PercentileTargetOperations +from ._percentile_operations import PercentileOperations +from ._collection_partition_region_operations import CollectionPartitionRegionOperations +from ._collection_partition_operations import CollectionPartitionOperations +from ._partition_key_range_id_operations import PartitionKeyRangeIdOperations +from ._partition_key_range_id_region_operations import PartitionKeyRangeIdRegionOperations +from ._graph_resources_operations import GraphResourcesOperations +from ._sql_resources_operations import SqlResourcesOperations +from ._mongo_db_resources_operations import MongoDBResourcesOperations +from ._table_resources_operations import TableResourcesOperations +from ._cassandra_resources_operations import CassandraResourcesOperations +from ._gremlin_resources_operations import GremlinResourcesOperations +from ._locations_operations import LocationsOperations +from ._data_transfer_jobs_operations import DataTransferJobsOperations +from ._cassandra_clusters_operations import CassandraClustersOperations +from ._cassandra_data_centers_operations import CassandraDataCentersOperations +from ._network_security_perimeter_configurations_operations import NetworkSecurityPerimeterConfigurationsOperations +from ._notebook_workspaces_operations import NotebookWorkspacesOperations +from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations +from ._private_link_resources_operations import PrivateLinkResourcesOperations +from ._restorable_database_accounts_operations import RestorableDatabaseAccountsOperations +from ._restorable_sql_databases_operations import RestorableSqlDatabasesOperations +from ._restorable_sql_containers_operations import RestorableSqlContainersOperations +from ._restorable_sql_resources_operations import RestorableSqlResourcesOperations +from ._restorable_mongodb_databases_operations import RestorableMongodbDatabasesOperations +from ._restorable_mongodb_collections_operations import RestorableMongodbCollectionsOperations +from ._restorable_mongodb_resources_operations import RestorableMongodbResourcesOperations +from ._restorable_gremlin_databases_operations import RestorableGremlinDatabasesOperations +from ._restorable_gremlin_graphs_operations import RestorableGremlinGraphsOperations +from ._restorable_gremlin_resources_operations import RestorableGremlinResourcesOperations +from ._restorable_tables_operations import RestorableTablesOperations +from ._restorable_table_resources_operations import RestorableTableResourcesOperations +from ._service_operations import ServiceOperations +from ._throughput_pools_operations import ThroughputPoolsOperations +from ._throughput_pool_operations import ThroughputPoolOperations +from ._throughput_pool_accounts_operations import ThroughputPoolAccountsOperations +from ._throughput_pool_account_operations import ThroughputPoolAccountOperations +from ._chaos_fault_operations import ChaosFaultOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "DatabaseAccountsOperations", + "Operations", + "DatabaseOperations", + "CollectionOperations", + "CollectionRegionOperations", + "DatabaseAccountRegionOperations", + "PercentileSourceTargetOperations", + "PercentileTargetOperations", + "PercentileOperations", + "CollectionPartitionRegionOperations", + "CollectionPartitionOperations", + "PartitionKeyRangeIdOperations", + "PartitionKeyRangeIdRegionOperations", + "GraphResourcesOperations", + "SqlResourcesOperations", + "MongoDBResourcesOperations", + "TableResourcesOperations", + "CassandraResourcesOperations", + "GremlinResourcesOperations", + "LocationsOperations", + "DataTransferJobsOperations", + "CassandraClustersOperations", + "CassandraDataCentersOperations", + "NetworkSecurityPerimeterConfigurationsOperations", + "NotebookWorkspacesOperations", + "PrivateEndpointConnectionsOperations", + "PrivateLinkResourcesOperations", + "RestorableDatabaseAccountsOperations", + "RestorableSqlDatabasesOperations", + "RestorableSqlContainersOperations", + "RestorableSqlResourcesOperations", + "RestorableMongodbDatabasesOperations", + "RestorableMongodbCollectionsOperations", + "RestorableMongodbResourcesOperations", + "RestorableGremlinDatabasesOperations", + "RestorableGremlinGraphsOperations", + "RestorableGremlinResourcesOperations", + "RestorableTablesOperations", + "RestorableTableResourcesOperations", + "ServiceOperations", + "ThroughputPoolsOperations", + "ThroughputPoolOperations", + "ThroughputPoolAccountsOperations", + "ThroughputPoolAccountOperations", + "ChaosFaultOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_cassandra_clusters_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_cassandra_clusters_operations.py index 314bb44cda3..aa57362888a 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_cassandra_clusters_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_cassandra_clusters_operations.py @@ -1,1729 +1,1729 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling - -from ... import models as _models -from ...operations._cassandra_clusters_operations import ( - build_create_update_request, - build_deallocate_request, - build_delete_request, - build_get_backup_request, - build_get_command_async_request, - build_get_request, - build_invoke_command_async_request, - build_invoke_command_request, - build_list_backups_request, - build_list_by_resource_group_request, - build_list_by_subscription_request, - build_list_command_request, - build_start_request, - build_status_request, - build_update_request, -) - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class CassandraClustersOperations: # pylint: disable=too-many-public-methods - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`cassandra_clusters` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.ClusterResource"]: - """List all managed Cassandra clusters in this subscription. - - :return: An iterator like instance of either ClusterResource or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.ClusterResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListClusters] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_by_subscription_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("ListClusters", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list_by_resource_group( - self, resource_group_name: str, **kwargs: Any - ) -> AsyncIterable["_models.ClusterResource"]: - """List all managed Cassandra clusters in this resource group. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :return: An iterator like instance of either ClusterResource or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.ClusterResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListClusters] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_by_resource_group_request( - resource_group_name=resource_group_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("ListClusters", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get(self, resource_group_name: str, cluster_name: str, **kwargs: Any) -> _models.ClusterResource: - """Get the properties of a managed Cassandra cluster. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :return: ClusterResource or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ClusterResource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ClusterResource] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ClusterResource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _delete_initial(self, resource_group_name: str, cluster_name: str, **kwargs: Any) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete(self, resource_group_name: str, cluster_name: str, **kwargs: Any) -> AsyncLROPoller[None]: - """Deletes a managed Cassandra cluster. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_initial( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - async def _create_update_initial( - self, - resource_group_name: str, - cluster_name: str, - body: Union[_models.ClusterResource, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _json = self._serialize.body(body, "ClusterResource") - - _request = build_create_update_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_update( - self, - resource_group_name: str, - cluster_name: str, - body: _models.ClusterResource, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ClusterResource]: - """Create or update a managed Cassandra cluster. When updating, you must specify all writable - properties. To update only some properties, use PATCH. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param body: The properties specifying the desired state of the managed Cassandra cluster. - Required. - :type body: ~azure.mgmt.cosmosdb.models.ClusterResource - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ClusterResource or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ClusterResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_update( - self, - resource_group_name: str, - cluster_name: str, - body: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ClusterResource]: - """Create or update a managed Cassandra cluster. When updating, you must specify all writable - properties. To update only some properties, use PATCH. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param body: The properties specifying the desired state of the managed Cassandra cluster. - Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ClusterResource or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ClusterResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_update( - self, - resource_group_name: str, - cluster_name: str, - body: Union[_models.ClusterResource, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.ClusterResource]: - """Create or update a managed Cassandra cluster. When updating, you must specify all writable - properties. To update only some properties, use PATCH. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param body: The properties specifying the desired state of the managed Cassandra cluster. Is - either a ClusterResource type or a IO[bytes] type. Required. - :type body: ~azure.mgmt.cosmosdb.models.ClusterResource or IO[bytes] - :return: An instance of AsyncLROPoller that returns either ClusterResource or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ClusterResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ClusterResource] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_update_initial( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ClusterResource", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ClusterResource].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ClusterResource]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _update_initial( - self, - resource_group_name: str, - cluster_name: str, - body: Union[_models.ClusterResource, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _json = self._serialize.body(body, "ClusterResource") - - _request = build_update_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_update( - self, - resource_group_name: str, - cluster_name: str, - body: _models.ClusterResource, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ClusterResource]: - """Updates some of the properties of a managed Cassandra cluster. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param body: Parameters to provide for specifying the managed Cassandra cluster. Required. - :type body: ~azure.mgmt.cosmosdb.models.ClusterResource - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ClusterResource or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ClusterResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_update( - self, - resource_group_name: str, - cluster_name: str, - body: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ClusterResource]: - """Updates some of the properties of a managed Cassandra cluster. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param body: Parameters to provide for specifying the managed Cassandra cluster. Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ClusterResource or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ClusterResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_update( - self, - resource_group_name: str, - cluster_name: str, - body: Union[_models.ClusterResource, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.ClusterResource]: - """Updates some of the properties of a managed Cassandra cluster. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param body: Parameters to provide for specifying the managed Cassandra cluster. Is either a - ClusterResource type or a IO[bytes] type. Required. - :type body: ~azure.mgmt.cosmosdb.models.ClusterResource or IO[bytes] - :return: An instance of AsyncLROPoller that returns either ClusterResource or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ClusterResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ClusterResource] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._update_initial( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ClusterResource", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ClusterResource].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ClusterResource]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _invoke_command_initial( - self, - resource_group_name: str, - cluster_name: str, - body: Union[_models.CommandPostBody, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _json = self._serialize.body(body, "CommandPostBody") - - _request = build_invoke_command_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_invoke_command( - self, - resource_group_name: str, - cluster_name: str, - body: _models.CommandPostBody, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.CommandOutput]: - """Invoke a command like nodetool for cassandra maintenance. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param body: Specification which command to run where. Required. - :type body: ~azure.mgmt.cosmosdb.models.CommandPostBody - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either CommandOutput or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.CommandOutput] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_invoke_command( - self, - resource_group_name: str, - cluster_name: str, - body: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.CommandOutput]: - """Invoke a command like nodetool for cassandra maintenance. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param body: Specification which command to run where. Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either CommandOutput or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.CommandOutput] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_invoke_command( - self, - resource_group_name: str, - cluster_name: str, - body: Union[_models.CommandPostBody, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.CommandOutput]: - """Invoke a command like nodetool for cassandra maintenance. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param body: Specification which command to run where. Is either a CommandPostBody type or a - IO[bytes] type. Required. - :type body: ~azure.mgmt.cosmosdb.models.CommandPostBody or IO[bytes] - :return: An instance of AsyncLROPoller that returns either CommandOutput or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.CommandOutput] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.CommandOutput] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._invoke_command_initial( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("CommandOutput", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.CommandOutput].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.CommandOutput]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _invoke_command_async_initial( - self, - resource_group_name: str, - cluster_name: str, - body: Union[_models.CommandPostBody, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _json = self._serialize.body(body, "CommandPostBody") - - _request = build_invoke_command_async_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_invoke_command_async( - self, - resource_group_name: str, - cluster_name: str, - body: _models.CommandPostBody, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.CommandPublicResource]: - """Invoke a command like nodetool for cassandra maintenance asynchronously. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param body: Specification which command to run where. Required. - :type body: ~azure.mgmt.cosmosdb.models.CommandPostBody - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either CommandPublicResource or the result - of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.CommandPublicResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_invoke_command_async( - self, - resource_group_name: str, - cluster_name: str, - body: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.CommandPublicResource]: - """Invoke a command like nodetool for cassandra maintenance asynchronously. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param body: Specification which command to run where. Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either CommandPublicResource or the result - of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.CommandPublicResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_invoke_command_async( - self, - resource_group_name: str, - cluster_name: str, - body: Union[_models.CommandPostBody, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.CommandPublicResource]: - """Invoke a command like nodetool for cassandra maintenance asynchronously. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param body: Specification which command to run where. Is either a CommandPostBody type or a - IO[bytes] type. Required. - :type body: ~azure.mgmt.cosmosdb.models.CommandPostBody or IO[bytes] - :return: An instance of AsyncLROPoller that returns either CommandPublicResource or the result - of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.CommandPublicResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.CommandPublicResource] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._invoke_command_async_initial( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("CommandPublicResource", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.CommandPublicResource].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.CommandPublicResource]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @distributed_trace - def list_command( - self, resource_group_name: str, cluster_name: str, **kwargs: Any - ) -> AsyncIterable["_models.CommandPublicResource"]: - """List all commands currently running on ring info. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :return: An iterator like instance of either CommandPublicResource or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.CommandPublicResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListCommands] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_command_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("ListCommands", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get_command_async( - self, resource_group_name: str, cluster_name: str, command_id: str, **kwargs: Any - ) -> _models.ListCommands: - """Get details about a specified command that was run asynchronously. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param command_id: Managed Cassandra cluster command id. Required. - :type command_id: str - :return: ListCommands or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ListCommands - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListCommands] = kwargs.pop("cls", None) - - _request = build_get_command_async_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - command_id=command_id, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ListCommands", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_backups( - self, resource_group_name: str, cluster_name: str, **kwargs: Any - ) -> AsyncIterable["_models.BackupResource"]: - """List the backups of this cluster that are available to restore. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :return: An iterator like instance of either BackupResource or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.BackupResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListBackups] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_backups_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("ListBackups", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get_backup( - self, resource_group_name: str, cluster_name: str, backup_id: str, **kwargs: Any - ) -> _models.BackupResource: - """Get the properties of an individual backup of this cluster that is available to restore. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param backup_id: Id of a restorable backup of a Cassandra cluster. Required. - :type backup_id: str - :return: BackupResource or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.BackupResource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.BackupResource] = kwargs.pop("cls", None) - - _request = build_get_backup_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - backup_id=backup_id, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("BackupResource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _deallocate_initial( - self, resource_group_name: str, cluster_name: str, x_ms_force_deallocate: Optional[str] = None, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_deallocate_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - subscription_id=self._config.subscription_id, - x_ms_force_deallocate=x_ms_force_deallocate, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_deallocate( - self, resource_group_name: str, cluster_name: str, x_ms_force_deallocate: Optional[str] = None, **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deallocate the Managed Cassandra Cluster and Associated Data Centers. Deallocation will - deallocate the host virtual machine of this cluster, and reserved the data disk. This won't do - anything on an already deallocated cluster. Use Start to restart the cluster. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param x_ms_force_deallocate: Force to deallocate a cluster of Cluster Type Production. Force - to deallocate a cluster of Cluster Type Production might cause data loss. Default value is - None. - :type x_ms_force_deallocate: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._deallocate_initial( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - x_ms_force_deallocate=x_ms_force_deallocate, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - async def _start_initial(self, resource_group_name: str, cluster_name: str, **kwargs: Any) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_start_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_start(self, resource_group_name: str, cluster_name: str, **kwargs: Any) -> AsyncLROPoller[None]: - """Start the Managed Cassandra Cluster and Associated Data Centers. Start will start the host - virtual machine of this cluster with reserved data disk. This won't do anything on an already - running cluster. Use Deallocate to deallocate the cluster. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._start_initial( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace_async - async def status( - self, resource_group_name: str, cluster_name: str, **kwargs: Any - ) -> _models.CassandraClusterPublicStatus: - """Gets the CPU, memory, and disk usage statistics for each Cassandra node in a cluster. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :return: CassandraClusterPublicStatus or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.CassandraClusterPublicStatus - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.CassandraClusterPublicStatus] = kwargs.pop("cls", None) - - _request = build_status_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("CassandraClusterPublicStatus", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ...operations._cassandra_clusters_operations import ( + build_create_update_request, + build_deallocate_request, + build_delete_request, + build_get_backup_request, + build_get_command_async_request, + build_get_request, + build_invoke_command_async_request, + build_invoke_command_request, + build_list_backups_request, + build_list_by_resource_group_request, + build_list_by_subscription_request, + build_list_command_request, + build_start_request, + build_status_request, + build_update_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class CassandraClustersOperations: # pylint: disable=too-many-public-methods + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`cassandra_clusters` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.ClusterResource"]: + """List all managed Cassandra clusters in this subscription. + + :return: An iterator like instance of either ClusterResource or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.ClusterResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ListClusters] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_subscription_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ListClusters", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_resource_group( + self, resource_group_name: str, **kwargs: Any + ) -> AsyncIterable["_models.ClusterResource"]: + """List all managed Cassandra clusters in this resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :return: An iterator like instance of either ClusterResource or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.ClusterResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ListClusters] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ListClusters", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get(self, resource_group_name: str, cluster_name: str, **kwargs: Any) -> _models.ClusterResource: + """Get the properties of a managed Cassandra cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :return: ClusterResource or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ClusterResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ClusterResource] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ClusterResource", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _delete_initial(self, resource_group_name: str, cluster_name: str, **kwargs: Any) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete(self, resource_group_name: str, cluster_name: str, **kwargs: Any) -> AsyncLROPoller[None]: + """Deletes a managed Cassandra cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + async def _create_update_initial( + self, + resource_group_name: str, + cluster_name: str, + body: Union[_models.ClusterResource, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "ClusterResource") + + _request = build_create_update_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_update( + self, + resource_group_name: str, + cluster_name: str, + body: _models.ClusterResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ClusterResource]: + """Create or update a managed Cassandra cluster. When updating, you must specify all writable + properties. To update only some properties, use PATCH. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param body: The properties specifying the desired state of the managed Cassandra cluster. + Required. + :type body: ~azure.mgmt.cosmosdb.models.ClusterResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ClusterResource or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ClusterResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_update( + self, + resource_group_name: str, + cluster_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ClusterResource]: + """Create or update a managed Cassandra cluster. When updating, you must specify all writable + properties. To update only some properties, use PATCH. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param body: The properties specifying the desired state of the managed Cassandra cluster. + Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ClusterResource or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ClusterResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_update( + self, + resource_group_name: str, + cluster_name: str, + body: Union[_models.ClusterResource, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.ClusterResource]: + """Create or update a managed Cassandra cluster. When updating, you must specify all writable + properties. To update only some properties, use PATCH. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param body: The properties specifying the desired state of the managed Cassandra cluster. Is + either a ClusterResource type or a IO[bytes] type. Required. + :type body: ~azure.mgmt.cosmosdb.models.ClusterResource or IO[bytes] + :return: An instance of AsyncLROPoller that returns either ClusterResource or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ClusterResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ClusterResource] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_update_initial( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + body=body, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ClusterResource", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ClusterResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ClusterResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _update_initial( + self, + resource_group_name: str, + cluster_name: str, + body: Union[_models.ClusterResource, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "ClusterResource") + + _request = build_update_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_update( + self, + resource_group_name: str, + cluster_name: str, + body: _models.ClusterResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ClusterResource]: + """Updates some of the properties of a managed Cassandra cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param body: Parameters to provide for specifying the managed Cassandra cluster. Required. + :type body: ~azure.mgmt.cosmosdb.models.ClusterResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ClusterResource or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ClusterResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update( + self, + resource_group_name: str, + cluster_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ClusterResource]: + """Updates some of the properties of a managed Cassandra cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param body: Parameters to provide for specifying the managed Cassandra cluster. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ClusterResource or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ClusterResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update( + self, + resource_group_name: str, + cluster_name: str, + body: Union[_models.ClusterResource, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.ClusterResource]: + """Updates some of the properties of a managed Cassandra cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param body: Parameters to provide for specifying the managed Cassandra cluster. Is either a + ClusterResource type or a IO[bytes] type. Required. + :type body: ~azure.mgmt.cosmosdb.models.ClusterResource or IO[bytes] + :return: An instance of AsyncLROPoller that returns either ClusterResource or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ClusterResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ClusterResource] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._update_initial( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + body=body, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ClusterResource", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ClusterResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ClusterResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _invoke_command_initial( + self, + resource_group_name: str, + cluster_name: str, + body: Union[_models.CommandPostBody, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "CommandPostBody") + + _request = build_invoke_command_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_invoke_command( + self, + resource_group_name: str, + cluster_name: str, + body: _models.CommandPostBody, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.CommandOutput]: + """Invoke a command like nodetool for cassandra maintenance. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param body: Specification which command to run where. Required. + :type body: ~azure.mgmt.cosmosdb.models.CommandPostBody + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either CommandOutput or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.CommandOutput] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_invoke_command( + self, + resource_group_name: str, + cluster_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.CommandOutput]: + """Invoke a command like nodetool for cassandra maintenance. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param body: Specification which command to run where. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either CommandOutput or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.CommandOutput] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_invoke_command( + self, + resource_group_name: str, + cluster_name: str, + body: Union[_models.CommandPostBody, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.CommandOutput]: + """Invoke a command like nodetool for cassandra maintenance. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param body: Specification which command to run where. Is either a CommandPostBody type or a + IO[bytes] type. Required. + :type body: ~azure.mgmt.cosmosdb.models.CommandPostBody or IO[bytes] + :return: An instance of AsyncLROPoller that returns either CommandOutput or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.CommandOutput] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CommandOutput] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._invoke_command_initial( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + body=body, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("CommandOutput", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.CommandOutput].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.CommandOutput]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _invoke_command_async_initial( + self, + resource_group_name: str, + cluster_name: str, + body: Union[_models.CommandPostBody, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "CommandPostBody") + + _request = build_invoke_command_async_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_invoke_command_async( + self, + resource_group_name: str, + cluster_name: str, + body: _models.CommandPostBody, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.CommandPublicResource]: + """Invoke a command like nodetool for cassandra maintenance asynchronously. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param body: Specification which command to run where. Required. + :type body: ~azure.mgmt.cosmosdb.models.CommandPostBody + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either CommandPublicResource or the result + of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.CommandPublicResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_invoke_command_async( + self, + resource_group_name: str, + cluster_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.CommandPublicResource]: + """Invoke a command like nodetool for cassandra maintenance asynchronously. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param body: Specification which command to run where. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either CommandPublicResource or the result + of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.CommandPublicResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_invoke_command_async( + self, + resource_group_name: str, + cluster_name: str, + body: Union[_models.CommandPostBody, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.CommandPublicResource]: + """Invoke a command like nodetool for cassandra maintenance asynchronously. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param body: Specification which command to run where. Is either a CommandPostBody type or a + IO[bytes] type. Required. + :type body: ~azure.mgmt.cosmosdb.models.CommandPostBody or IO[bytes] + :return: An instance of AsyncLROPoller that returns either CommandPublicResource or the result + of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.CommandPublicResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CommandPublicResource] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._invoke_command_async_initial( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + body=body, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("CommandPublicResource", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.CommandPublicResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.CommandPublicResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def list_command( + self, resource_group_name: str, cluster_name: str, **kwargs: Any + ) -> AsyncIterable["_models.CommandPublicResource"]: + """List all commands currently running on ring info. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :return: An iterator like instance of either CommandPublicResource or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.CommandPublicResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ListCommands] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_command_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ListCommands", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get_command_async( + self, resource_group_name: str, cluster_name: str, command_id: str, **kwargs: Any + ) -> _models.ListCommands: + """Get details about a specified command that was run asynchronously. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param command_id: Managed Cassandra cluster command id. Required. + :type command_id: str + :return: ListCommands or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ListCommands + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ListCommands] = kwargs.pop("cls", None) + + _request = build_get_command_async_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + command_id=command_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ListCommands", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_backups( + self, resource_group_name: str, cluster_name: str, **kwargs: Any + ) -> AsyncIterable["_models.BackupResource"]: + """List the backups of this cluster that are available to restore. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :return: An iterator like instance of either BackupResource or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.BackupResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ListBackups] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_backups_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ListBackups", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get_backup( + self, resource_group_name: str, cluster_name: str, backup_id: str, **kwargs: Any + ) -> _models.BackupResource: + """Get the properties of an individual backup of this cluster that is available to restore. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param backup_id: Id of a restorable backup of a Cassandra cluster. Required. + :type backup_id: str + :return: BackupResource or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.BackupResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.BackupResource] = kwargs.pop("cls", None) + + _request = build_get_backup_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + backup_id=backup_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("BackupResource", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _deallocate_initial( + self, resource_group_name: str, cluster_name: str, x_ms_force_deallocate: Optional[str] = None, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_deallocate_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + subscription_id=self._config.subscription_id, + x_ms_force_deallocate=x_ms_force_deallocate, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_deallocate( + self, resource_group_name: str, cluster_name: str, x_ms_force_deallocate: Optional[str] = None, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deallocate the Managed Cassandra Cluster and Associated Data Centers. Deallocation will + deallocate the host virtual machine of this cluster, and reserved the data disk. This won't do + anything on an already deallocated cluster. Use Start to restart the cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param x_ms_force_deallocate: Force to deallocate a cluster of Cluster Type Production. Force + to deallocate a cluster of Cluster Type Production might cause data loss. Default value is + None. + :type x_ms_force_deallocate: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._deallocate_initial( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + x_ms_force_deallocate=x_ms_force_deallocate, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + async def _start_initial(self, resource_group_name: str, cluster_name: str, **kwargs: Any) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_start_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_start(self, resource_group_name: str, cluster_name: str, **kwargs: Any) -> AsyncLROPoller[None]: + """Start the Managed Cassandra Cluster and Associated Data Centers. Start will start the host + virtual machine of this cluster with reserved data disk. This won't do anything on an already + running cluster. Use Deallocate to deallocate the cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._start_initial( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace_async + async def status( + self, resource_group_name: str, cluster_name: str, **kwargs: Any + ) -> _models.CassandraClusterPublicStatus: + """Gets the CPU, memory, and disk usage statistics for each Cassandra node in a cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :return: CassandraClusterPublicStatus or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.CassandraClusterPublicStatus + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.CassandraClusterPublicStatus] = kwargs.pop("cls", None) + + _request = build_status_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("CassandraClusterPublicStatus", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_cassandra_data_centers_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_cassandra_data_centers_operations.py index 34ecce2b5fb..093aa15cfd5 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_cassandra_data_centers_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_cassandra_data_centers_operations.py @@ -1,731 +1,731 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling - -from ... import models as _models -from ...operations._cassandra_data_centers_operations import ( - build_create_update_request, - build_delete_request, - build_get_request, - build_list_request, - build_update_request, -) - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class CassandraDataCentersOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`cassandra_data_centers` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, resource_group_name: str, cluster_name: str, **kwargs: Any - ) -> AsyncIterable["_models.DataCenterResource"]: - """List all data centers in a particular managed Cassandra cluster. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :return: An iterator like instance of either DataCenterResource or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.DataCenterResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListDataCenters] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("ListDataCenters", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get( - self, resource_group_name: str, cluster_name: str, data_center_name: str, **kwargs: Any - ) -> _models.DataCenterResource: - """Get the properties of a managed Cassandra data center. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param data_center_name: Data center name in a managed Cassandra cluster. Required. - :type data_center_name: str - :return: DataCenterResource or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.DataCenterResource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DataCenterResource] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - data_center_name=data_center_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DataCenterResource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _delete_initial( - self, resource_group_name: str, cluster_name: str, data_center_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - data_center_name=data_center_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete( - self, resource_group_name: str, cluster_name: str, data_center_name: str, **kwargs: Any - ) -> AsyncLROPoller[None]: - """Delete a managed Cassandra data center. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param data_center_name: Data center name in a managed Cassandra cluster. Required. - :type data_center_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_initial( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - data_center_name=data_center_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - async def _create_update_initial( - self, - resource_group_name: str, - cluster_name: str, - data_center_name: str, - body: Union[_models.DataCenterResource, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _json = self._serialize.body(body, "DataCenterResource") - - _request = build_create_update_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - data_center_name=data_center_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_update( - self, - resource_group_name: str, - cluster_name: str, - data_center_name: str, - body: _models.DataCenterResource, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.DataCenterResource]: - """Create or update a managed Cassandra data center. When updating, overwrite all properties. To - update only some properties, use PATCH. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param data_center_name: Data center name in a managed Cassandra cluster. Required. - :type data_center_name: str - :param body: Parameters specifying the managed Cassandra data center. Required. - :type body: ~azure.mgmt.cosmosdb.models.DataCenterResource - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either DataCenterResource or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.DataCenterResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_update( - self, - resource_group_name: str, - cluster_name: str, - data_center_name: str, - body: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.DataCenterResource]: - """Create or update a managed Cassandra data center. When updating, overwrite all properties. To - update only some properties, use PATCH. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param data_center_name: Data center name in a managed Cassandra cluster. Required. - :type data_center_name: str - :param body: Parameters specifying the managed Cassandra data center. Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either DataCenterResource or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.DataCenterResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_update( - self, - resource_group_name: str, - cluster_name: str, - data_center_name: str, - body: Union[_models.DataCenterResource, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.DataCenterResource]: - """Create or update a managed Cassandra data center. When updating, overwrite all properties. To - update only some properties, use PATCH. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param data_center_name: Data center name in a managed Cassandra cluster. Required. - :type data_center_name: str - :param body: Parameters specifying the managed Cassandra data center. Is either a - DataCenterResource type or a IO[bytes] type. Required. - :type body: ~azure.mgmt.cosmosdb.models.DataCenterResource or IO[bytes] - :return: An instance of AsyncLROPoller that returns either DataCenterResource or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.DataCenterResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.DataCenterResource] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_update_initial( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - data_center_name=data_center_name, - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("DataCenterResource", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.DataCenterResource].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.DataCenterResource]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _update_initial( - self, - resource_group_name: str, - cluster_name: str, - data_center_name: str, - body: Union[_models.DataCenterResource, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _json = self._serialize.body(body, "DataCenterResource") - - _request = build_update_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - data_center_name=data_center_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_update( - self, - resource_group_name: str, - cluster_name: str, - data_center_name: str, - body: _models.DataCenterResource, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.DataCenterResource]: - """Update some of the properties of a managed Cassandra data center. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param data_center_name: Data center name in a managed Cassandra cluster. Required. - :type data_center_name: str - :param body: Parameters to provide for specifying the managed Cassandra data center. Required. - :type body: ~azure.mgmt.cosmosdb.models.DataCenterResource - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either DataCenterResource or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.DataCenterResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_update( - self, - resource_group_name: str, - cluster_name: str, - data_center_name: str, - body: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.DataCenterResource]: - """Update some of the properties of a managed Cassandra data center. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param data_center_name: Data center name in a managed Cassandra cluster. Required. - :type data_center_name: str - :param body: Parameters to provide for specifying the managed Cassandra data center. Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either DataCenterResource or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.DataCenterResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_update( - self, - resource_group_name: str, - cluster_name: str, - data_center_name: str, - body: Union[_models.DataCenterResource, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.DataCenterResource]: - """Update some of the properties of a managed Cassandra data center. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param data_center_name: Data center name in a managed Cassandra cluster. Required. - :type data_center_name: str - :param body: Parameters to provide for specifying the managed Cassandra data center. Is either - a DataCenterResource type or a IO[bytes] type. Required. - :type body: ~azure.mgmt.cosmosdb.models.DataCenterResource or IO[bytes] - :return: An instance of AsyncLROPoller that returns either DataCenterResource or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.DataCenterResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.DataCenterResource] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._update_initial( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - data_center_name=data_center_name, - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("DataCenterResource", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.DataCenterResource].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.DataCenterResource]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ...operations._cassandra_data_centers_operations import ( + build_create_update_request, + build_delete_request, + build_get_request, + build_list_request, + build_update_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class CassandraDataCentersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`cassandra_data_centers` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, resource_group_name: str, cluster_name: str, **kwargs: Any + ) -> AsyncIterable["_models.DataCenterResource"]: + """List all data centers in a particular managed Cassandra cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :return: An iterator like instance of either DataCenterResource or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.DataCenterResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ListDataCenters] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ListDataCenters", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get( + self, resource_group_name: str, cluster_name: str, data_center_name: str, **kwargs: Any + ) -> _models.DataCenterResource: + """Get the properties of a managed Cassandra data center. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param data_center_name: Data center name in a managed Cassandra cluster. Required. + :type data_center_name: str + :return: DataCenterResource or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.DataCenterResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DataCenterResource] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + data_center_name=data_center_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DataCenterResource", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _delete_initial( + self, resource_group_name: str, cluster_name: str, data_center_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + data_center_name=data_center_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete( + self, resource_group_name: str, cluster_name: str, data_center_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Delete a managed Cassandra data center. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param data_center_name: Data center name in a managed Cassandra cluster. Required. + :type data_center_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + data_center_name=data_center_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + async def _create_update_initial( + self, + resource_group_name: str, + cluster_name: str, + data_center_name: str, + body: Union[_models.DataCenterResource, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "DataCenterResource") + + _request = build_create_update_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + data_center_name=data_center_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_update( + self, + resource_group_name: str, + cluster_name: str, + data_center_name: str, + body: _models.DataCenterResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DataCenterResource]: + """Create or update a managed Cassandra data center. When updating, overwrite all properties. To + update only some properties, use PATCH. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param data_center_name: Data center name in a managed Cassandra cluster. Required. + :type data_center_name: str + :param body: Parameters specifying the managed Cassandra data center. Required. + :type body: ~azure.mgmt.cosmosdb.models.DataCenterResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either DataCenterResource or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.DataCenterResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_update( + self, + resource_group_name: str, + cluster_name: str, + data_center_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DataCenterResource]: + """Create or update a managed Cassandra data center. When updating, overwrite all properties. To + update only some properties, use PATCH. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param data_center_name: Data center name in a managed Cassandra cluster. Required. + :type data_center_name: str + :param body: Parameters specifying the managed Cassandra data center. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either DataCenterResource or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.DataCenterResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_update( + self, + resource_group_name: str, + cluster_name: str, + data_center_name: str, + body: Union[_models.DataCenterResource, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.DataCenterResource]: + """Create or update a managed Cassandra data center. When updating, overwrite all properties. To + update only some properties, use PATCH. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param data_center_name: Data center name in a managed Cassandra cluster. Required. + :type data_center_name: str + :param body: Parameters specifying the managed Cassandra data center. Is either a + DataCenterResource type or a IO[bytes] type. Required. + :type body: ~azure.mgmt.cosmosdb.models.DataCenterResource or IO[bytes] + :return: An instance of AsyncLROPoller that returns either DataCenterResource or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.DataCenterResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DataCenterResource] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_update_initial( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + data_center_name=data_center_name, + body=body, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("DataCenterResource", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.DataCenterResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.DataCenterResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _update_initial( + self, + resource_group_name: str, + cluster_name: str, + data_center_name: str, + body: Union[_models.DataCenterResource, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "DataCenterResource") + + _request = build_update_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + data_center_name=data_center_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_update( + self, + resource_group_name: str, + cluster_name: str, + data_center_name: str, + body: _models.DataCenterResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DataCenterResource]: + """Update some of the properties of a managed Cassandra data center. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param data_center_name: Data center name in a managed Cassandra cluster. Required. + :type data_center_name: str + :param body: Parameters to provide for specifying the managed Cassandra data center. Required. + :type body: ~azure.mgmt.cosmosdb.models.DataCenterResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either DataCenterResource or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.DataCenterResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update( + self, + resource_group_name: str, + cluster_name: str, + data_center_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DataCenterResource]: + """Update some of the properties of a managed Cassandra data center. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param data_center_name: Data center name in a managed Cassandra cluster. Required. + :type data_center_name: str + :param body: Parameters to provide for specifying the managed Cassandra data center. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either DataCenterResource or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.DataCenterResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update( + self, + resource_group_name: str, + cluster_name: str, + data_center_name: str, + body: Union[_models.DataCenterResource, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.DataCenterResource]: + """Update some of the properties of a managed Cassandra data center. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param data_center_name: Data center name in a managed Cassandra cluster. Required. + :type data_center_name: str + :param body: Parameters to provide for specifying the managed Cassandra data center. Is either + a DataCenterResource type or a IO[bytes] type. Required. + :type body: ~azure.mgmt.cosmosdb.models.DataCenterResource or IO[bytes] + :return: An instance of AsyncLROPoller that returns either DataCenterResource or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.DataCenterResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DataCenterResource] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._update_initial( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + data_center_name=data_center_name, + body=body, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("DataCenterResource", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.DataCenterResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.DataCenterResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_cassandra_resources_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_cassandra_resources_operations.py index 20489eadbbb..955c2e5507c 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_cassandra_resources_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_cassandra_resources_operations.py @@ -1,3191 +1,3191 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling - -from ... import models as _models -from ...operations._cassandra_resources_operations import ( - build_create_update_cassandra_keyspace_request, - build_create_update_cassandra_table_request, - build_create_update_cassandra_view_request, - build_delete_cassandra_keyspace_request, - build_delete_cassandra_table_request, - build_delete_cassandra_view_request, - build_get_cassandra_keyspace_request, - build_get_cassandra_keyspace_throughput_request, - build_get_cassandra_table_request, - build_get_cassandra_table_throughput_request, - build_get_cassandra_view_request, - build_get_cassandra_view_throughput_request, - build_list_cassandra_keyspaces_request, - build_list_cassandra_tables_request, - build_list_cassandra_views_request, - build_migrate_cassandra_keyspace_to_autoscale_request, - build_migrate_cassandra_keyspace_to_manual_throughput_request, - build_migrate_cassandra_table_to_autoscale_request, - build_migrate_cassandra_table_to_manual_throughput_request, - build_migrate_cassandra_view_to_autoscale_request, - build_migrate_cassandra_view_to_manual_throughput_request, - build_update_cassandra_keyspace_throughput_request, - build_update_cassandra_table_throughput_request, - build_update_cassandra_view_throughput_request, -) - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class CassandraResourcesOperations: # pylint: disable=too-many-public-methods - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`cassandra_resources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_cassandra_keyspaces( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> AsyncIterable["_models.CassandraKeyspaceGetResults"]: - """Lists the Cassandra keyspaces under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either CassandraKeyspaceGetResults or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.CassandraKeyspaceGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.CassandraKeyspaceListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_cassandra_keyspaces_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("CassandraKeyspaceListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get_cassandra_keyspace( - self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any - ) -> _models.CassandraKeyspaceGetResults: - """Gets the Cassandra keyspaces under an existing Azure Cosmos DB database account with the - provided name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :return: CassandraKeyspaceGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.CassandraKeyspaceGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.CassandraKeyspaceGetResults] = kwargs.pop("cls", None) - - _request = build_get_cassandra_keyspace_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("CassandraKeyspaceGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _create_update_cassandra_keyspace_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - create_update_cassandra_keyspace_parameters: Union[_models.CassandraKeyspaceCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_cassandra_keyspace_parameters, (IOBase, bytes)): - _content = create_update_cassandra_keyspace_parameters - else: - _json = self._serialize.body( - create_update_cassandra_keyspace_parameters, "CassandraKeyspaceCreateUpdateParameters" - ) - - _request = build_create_update_cassandra_keyspace_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_update_cassandra_keyspace( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - create_update_cassandra_keyspace_parameters: _models.CassandraKeyspaceCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.CassandraKeyspaceGetResults]: - """Create or update an Azure Cosmos DB Cassandra keyspace. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param create_update_cassandra_keyspace_parameters: The parameters to provide for the current - Cassandra keyspace. Required. - :type create_update_cassandra_keyspace_parameters: - ~azure.mgmt.cosmosdb.models.CassandraKeyspaceCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either CassandraKeyspaceGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.CassandraKeyspaceGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_update_cassandra_keyspace( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - create_update_cassandra_keyspace_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.CassandraKeyspaceGetResults]: - """Create or update an Azure Cosmos DB Cassandra keyspace. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param create_update_cassandra_keyspace_parameters: The parameters to provide for the current - Cassandra keyspace. Required. - :type create_update_cassandra_keyspace_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either CassandraKeyspaceGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.CassandraKeyspaceGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_update_cassandra_keyspace( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - create_update_cassandra_keyspace_parameters: Union[_models.CassandraKeyspaceCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.CassandraKeyspaceGetResults]: - """Create or update an Azure Cosmos DB Cassandra keyspace. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param create_update_cassandra_keyspace_parameters: The parameters to provide for the current - Cassandra keyspace. Is either a CassandraKeyspaceCreateUpdateParameters type or a IO[bytes] - type. Required. - :type create_update_cassandra_keyspace_parameters: - ~azure.mgmt.cosmosdb.models.CassandraKeyspaceCreateUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either CassandraKeyspaceGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.CassandraKeyspaceGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.CassandraKeyspaceGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_update_cassandra_keyspace_initial( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - create_update_cassandra_keyspace_parameters=create_update_cassandra_keyspace_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("CassandraKeyspaceGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.CassandraKeyspaceGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.CassandraKeyspaceGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _delete_cassandra_keyspace_initial( - self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_cassandra_keyspace_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete_cassandra_keyspace( - self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes an existing Azure Cosmos DB Cassandra keyspace. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_cassandra_keyspace_initial( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace_async - async def get_cassandra_keyspace_throughput( - self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any - ) -> _models.ThroughputSettingsGetResults: - """Gets the RUs per second of the Cassandra Keyspace under an existing Azure Cosmos DB database - account with the provided name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :return: ThroughputSettingsGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - - _request = build_get_cassandra_keyspace_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _update_cassandra_keyspace_throughput_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(update_throughput_parameters, (IOBase, bytes)): - _content = update_throughput_parameters - else: - _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") - - _request = build_update_cassandra_keyspace_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_update_cassandra_keyspace_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Cassandra Keyspace. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current Cassandra Keyspace. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_update_cassandra_keyspace_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - update_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Cassandra Keyspace. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current Cassandra Keyspace. Required. - :type update_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_update_cassandra_keyspace_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Cassandra Keyspace. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current Cassandra Keyspace. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] - type. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._update_cassandra_keyspace_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - update_throughput_parameters=update_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _migrate_cassandra_keyspace_to_autoscale_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_cassandra_keyspace_to_autoscale_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_migrate_cassandra_keyspace_to_autoscale( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB Cassandra Keyspace from manual throughput to autoscale. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._migrate_cassandra_keyspace_to_autoscale_initial( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _migrate_cassandra_keyspace_to_manual_throughput_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_cassandra_keyspace_to_manual_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_migrate_cassandra_keyspace_to_manual_throughput( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB Cassandra Keyspace from autoscale to manual throughput. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._migrate_cassandra_keyspace_to_manual_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @distributed_trace - def list_cassandra_tables( - self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any - ) -> AsyncIterable["_models.CassandraTableGetResults"]: - """Lists the Cassandra table under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :return: An iterator like instance of either CassandraTableGetResults or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.CassandraTableGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.CassandraTableListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_cassandra_tables_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("CassandraTableListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get_cassandra_table( - self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any - ) -> _models.CassandraTableGetResults: - """Gets the Cassandra table under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :return: CassandraTableGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.CassandraTableGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.CassandraTableGetResults] = kwargs.pop("cls", None) - - _request = build_get_cassandra_table_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - table_name=table_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("CassandraTableGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _create_update_cassandra_table_initial( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - table_name: str, - create_update_cassandra_table_parameters: Union[_models.CassandraTableCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_cassandra_table_parameters, (IOBase, bytes)): - _content = create_update_cassandra_table_parameters - else: - _json = self._serialize.body( - create_update_cassandra_table_parameters, "CassandraTableCreateUpdateParameters" - ) - - _request = build_create_update_cassandra_table_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - table_name=table_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_update_cassandra_table( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - table_name: str, - create_update_cassandra_table_parameters: _models.CassandraTableCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.CassandraTableGetResults]: - """Create or update an Azure Cosmos DB Cassandra Table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :param create_update_cassandra_table_parameters: The parameters to provide for the current - Cassandra Table. Required. - :type create_update_cassandra_table_parameters: - ~azure.mgmt.cosmosdb.models.CassandraTableCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either CassandraTableGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.CassandraTableGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_update_cassandra_table( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - table_name: str, - create_update_cassandra_table_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.CassandraTableGetResults]: - """Create or update an Azure Cosmos DB Cassandra Table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :param create_update_cassandra_table_parameters: The parameters to provide for the current - Cassandra Table. Required. - :type create_update_cassandra_table_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either CassandraTableGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.CassandraTableGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_update_cassandra_table( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - table_name: str, - create_update_cassandra_table_parameters: Union[_models.CassandraTableCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.CassandraTableGetResults]: - """Create or update an Azure Cosmos DB Cassandra Table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :param create_update_cassandra_table_parameters: The parameters to provide for the current - Cassandra Table. Is either a CassandraTableCreateUpdateParameters type or a IO[bytes] type. - Required. - :type create_update_cassandra_table_parameters: - ~azure.mgmt.cosmosdb.models.CassandraTableCreateUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either CassandraTableGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.CassandraTableGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.CassandraTableGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_update_cassandra_table_initial( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - table_name=table_name, - create_update_cassandra_table_parameters=create_update_cassandra_table_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("CassandraTableGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.CassandraTableGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.CassandraTableGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _delete_cassandra_table_initial( - self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_cassandra_table_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - table_name=table_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete_cassandra_table( - self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes an existing Azure Cosmos DB Cassandra table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_cassandra_table_initial( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - table_name=table_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace_async - async def get_cassandra_table_throughput( - self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any - ) -> _models.ThroughputSettingsGetResults: - """Gets the RUs per second of the Cassandra table under an existing Azure Cosmos DB database - account with the provided name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :return: ThroughputSettingsGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - - _request = build_get_cassandra_table_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - table_name=table_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _update_cassandra_table_throughput_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - table_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(update_throughput_parameters, (IOBase, bytes)): - _content = update_throughput_parameters - else: - _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") - - _request = build_update_cassandra_table_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - table_name=table_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_update_cassandra_table_throughput( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - table_name: str, - update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Cassandra table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current Cassandra table. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_update_cassandra_table_throughput( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - table_name: str, - update_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Cassandra table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current Cassandra table. Required. - :type update_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_update_cassandra_table_throughput( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - table_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Cassandra table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current Cassandra table. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] - type. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._update_cassandra_table_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - table_name=table_name, - update_throughput_parameters=update_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _migrate_cassandra_table_to_autoscale_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_cassandra_table_to_autoscale_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - table_name=table_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_migrate_cassandra_table_to_autoscale( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB Cassandra table from manual throughput to autoscale. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._migrate_cassandra_table_to_autoscale_initial( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - table_name=table_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _migrate_cassandra_table_to_manual_throughput_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_cassandra_table_to_manual_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - table_name=table_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_migrate_cassandra_table_to_manual_throughput( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB Cassandra table from autoscale to manual throughput. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._migrate_cassandra_table_to_manual_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - table_name=table_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @distributed_trace - def list_cassandra_views( - self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any - ) -> AsyncIterable["_models.CassandraViewGetResults"]: - """Lists the Cassandra materialized views under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :return: An iterator like instance of either CassandraViewGetResults or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.CassandraViewGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.CassandraViewListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_cassandra_views_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("CassandraViewListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get_cassandra_view( - self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any - ) -> _models.CassandraViewGetResults: - """Gets the Cassandra view under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param view_name: Cosmos DB view name. Required. - :type view_name: str - :return: CassandraViewGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.CassandraViewGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.CassandraViewGetResults] = kwargs.pop("cls", None) - - _request = build_get_cassandra_view_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - view_name=view_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("CassandraViewGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _create_update_cassandra_view_initial( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - view_name: str, - create_update_cassandra_view_parameters: Union[_models.CassandraViewCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_cassandra_view_parameters, (IOBase, bytes)): - _content = create_update_cassandra_view_parameters - else: - _json = self._serialize.body(create_update_cassandra_view_parameters, "CassandraViewCreateUpdateParameters") - - _request = build_create_update_cassandra_view_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - view_name=view_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_update_cassandra_view( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - view_name: str, - create_update_cassandra_view_parameters: _models.CassandraViewCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.CassandraViewGetResults]: - """Create or update an Azure Cosmos DB Cassandra View. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param view_name: Cosmos DB view name. Required. - :type view_name: str - :param create_update_cassandra_view_parameters: The parameters to provide for the current - Cassandra View. Required. - :type create_update_cassandra_view_parameters: - ~azure.mgmt.cosmosdb.models.CassandraViewCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either CassandraViewGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.CassandraViewGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_update_cassandra_view( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - view_name: str, - create_update_cassandra_view_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.CassandraViewGetResults]: - """Create or update an Azure Cosmos DB Cassandra View. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param view_name: Cosmos DB view name. Required. - :type view_name: str - :param create_update_cassandra_view_parameters: The parameters to provide for the current - Cassandra View. Required. - :type create_update_cassandra_view_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either CassandraViewGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.CassandraViewGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_update_cassandra_view( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - view_name: str, - create_update_cassandra_view_parameters: Union[_models.CassandraViewCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.CassandraViewGetResults]: - """Create or update an Azure Cosmos DB Cassandra View. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param view_name: Cosmos DB view name. Required. - :type view_name: str - :param create_update_cassandra_view_parameters: The parameters to provide for the current - Cassandra View. Is either a CassandraViewCreateUpdateParameters type or a IO[bytes] type. - Required. - :type create_update_cassandra_view_parameters: - ~azure.mgmt.cosmosdb.models.CassandraViewCreateUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either CassandraViewGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.CassandraViewGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.CassandraViewGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_update_cassandra_view_initial( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - view_name=view_name, - create_update_cassandra_view_parameters=create_update_cassandra_view_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("CassandraViewGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.CassandraViewGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.CassandraViewGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _delete_cassandra_view_initial( - self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_cassandra_view_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - view_name=view_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202, 204]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete_cassandra_view( - self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes an existing Azure Cosmos DB Cassandra view. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param view_name: Cosmos DB view name. Required. - :type view_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_cassandra_view_initial( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - view_name=view_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace_async - async def get_cassandra_view_throughput( - self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any - ) -> _models.ThroughputSettingsGetResults: - """Gets the RUs per second of the Cassandra view under an existing Azure Cosmos DB database - account with the provided name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param view_name: Cosmos DB view name. Required. - :type view_name: str - :return: ThroughputSettingsGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - - _request = build_get_cassandra_view_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - view_name=view_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _update_cassandra_view_throughput_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - view_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(update_throughput_parameters, (IOBase, bytes)): - _content = update_throughput_parameters - else: - _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") - - _request = build_update_cassandra_view_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - view_name=view_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_update_cassandra_view_throughput( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - view_name: str, - update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Cassandra view. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param view_name: Cosmos DB view name. Required. - :type view_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current Cassandra view. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_update_cassandra_view_throughput( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - view_name: str, - update_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Cassandra view. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param view_name: Cosmos DB view name. Required. - :type view_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current Cassandra view. Required. - :type update_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_update_cassandra_view_throughput( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - view_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Cassandra view. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param view_name: Cosmos DB view name. Required. - :type view_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current Cassandra view. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] - type. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._update_cassandra_view_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - view_name=view_name, - update_throughput_parameters=update_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _migrate_cassandra_view_to_autoscale_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_cassandra_view_to_autoscale_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - view_name=view_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_migrate_cassandra_view_to_autoscale( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB Cassandra view from manual throughput to autoscale. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param view_name: Cosmos DB view name. Required. - :type view_name: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._migrate_cassandra_view_to_autoscale_initial( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - view_name=view_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _migrate_cassandra_view_to_manual_throughput_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_cassandra_view_to_manual_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - view_name=view_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_migrate_cassandra_view_to_manual_throughput( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB Cassandra view from autoscale to manual throughput. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param view_name: Cosmos DB view name. Required. - :type view_name: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._migrate_cassandra_view_to_manual_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - view_name=view_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ...operations._cassandra_resources_operations import ( + build_create_update_cassandra_keyspace_request, + build_create_update_cassandra_table_request, + build_create_update_cassandra_view_request, + build_delete_cassandra_keyspace_request, + build_delete_cassandra_table_request, + build_delete_cassandra_view_request, + build_get_cassandra_keyspace_request, + build_get_cassandra_keyspace_throughput_request, + build_get_cassandra_table_request, + build_get_cassandra_table_throughput_request, + build_get_cassandra_view_request, + build_get_cassandra_view_throughput_request, + build_list_cassandra_keyspaces_request, + build_list_cassandra_tables_request, + build_list_cassandra_views_request, + build_migrate_cassandra_keyspace_to_autoscale_request, + build_migrate_cassandra_keyspace_to_manual_throughput_request, + build_migrate_cassandra_table_to_autoscale_request, + build_migrate_cassandra_table_to_manual_throughput_request, + build_migrate_cassandra_view_to_autoscale_request, + build_migrate_cassandra_view_to_manual_throughput_request, + build_update_cassandra_keyspace_throughput_request, + build_update_cassandra_table_throughput_request, + build_update_cassandra_view_throughput_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class CassandraResourcesOperations: # pylint: disable=too-many-public-methods + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`cassandra_resources` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_cassandra_keyspaces( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> AsyncIterable["_models.CassandraKeyspaceGetResults"]: + """Lists the Cassandra keyspaces under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either CassandraKeyspaceGetResults or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.CassandraKeyspaceGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.CassandraKeyspaceListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_cassandra_keyspaces_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("CassandraKeyspaceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get_cassandra_keyspace( + self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any + ) -> _models.CassandraKeyspaceGetResults: + """Gets the Cassandra keyspaces under an existing Azure Cosmos DB database account with the + provided name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :return: CassandraKeyspaceGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.CassandraKeyspaceGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.CassandraKeyspaceGetResults] = kwargs.pop("cls", None) + + _request = build_get_cassandra_keyspace_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("CassandraKeyspaceGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_update_cassandra_keyspace_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + create_update_cassandra_keyspace_parameters: Union[_models.CassandraKeyspaceCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_cassandra_keyspace_parameters, (IOBase, bytes)): + _content = create_update_cassandra_keyspace_parameters + else: + _json = self._serialize.body( + create_update_cassandra_keyspace_parameters, "CassandraKeyspaceCreateUpdateParameters" + ) + + _request = build_create_update_cassandra_keyspace_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_update_cassandra_keyspace( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + create_update_cassandra_keyspace_parameters: _models.CassandraKeyspaceCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.CassandraKeyspaceGetResults]: + """Create or update an Azure Cosmos DB Cassandra keyspace. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param create_update_cassandra_keyspace_parameters: The parameters to provide for the current + Cassandra keyspace. Required. + :type create_update_cassandra_keyspace_parameters: + ~azure.mgmt.cosmosdb.models.CassandraKeyspaceCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either CassandraKeyspaceGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.CassandraKeyspaceGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_update_cassandra_keyspace( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + create_update_cassandra_keyspace_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.CassandraKeyspaceGetResults]: + """Create or update an Azure Cosmos DB Cassandra keyspace. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param create_update_cassandra_keyspace_parameters: The parameters to provide for the current + Cassandra keyspace. Required. + :type create_update_cassandra_keyspace_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either CassandraKeyspaceGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.CassandraKeyspaceGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_update_cassandra_keyspace( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + create_update_cassandra_keyspace_parameters: Union[_models.CassandraKeyspaceCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.CassandraKeyspaceGetResults]: + """Create or update an Azure Cosmos DB Cassandra keyspace. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param create_update_cassandra_keyspace_parameters: The parameters to provide for the current + Cassandra keyspace. Is either a CassandraKeyspaceCreateUpdateParameters type or a IO[bytes] + type. Required. + :type create_update_cassandra_keyspace_parameters: + ~azure.mgmt.cosmosdb.models.CassandraKeyspaceCreateUpdateParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either CassandraKeyspaceGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.CassandraKeyspaceGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CassandraKeyspaceGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_update_cassandra_keyspace_initial( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + create_update_cassandra_keyspace_parameters=create_update_cassandra_keyspace_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("CassandraKeyspaceGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.CassandraKeyspaceGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.CassandraKeyspaceGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_cassandra_keyspace_initial( + self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_cassandra_keyspace_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete_cassandra_keyspace( + self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes an existing Azure Cosmos DB Cassandra keyspace. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_cassandra_keyspace_initial( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace_async + async def get_cassandra_keyspace_throughput( + self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any + ) -> _models.ThroughputSettingsGetResults: + """Gets the RUs per second of the Cassandra Keyspace under an existing Azure Cosmos DB database + account with the provided name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :return: ThroughputSettingsGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + + _request = build_get_cassandra_keyspace_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _update_cassandra_keyspace_throughput_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(update_throughput_parameters, (IOBase, bytes)): + _content = update_throughput_parameters + else: + _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") + + _request = build_update_cassandra_keyspace_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_update_cassandra_keyspace_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Cassandra Keyspace. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current Cassandra Keyspace. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update_cassandra_keyspace_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + update_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Cassandra Keyspace. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current Cassandra Keyspace. Required. + :type update_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update_cassandra_keyspace_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Cassandra Keyspace. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current Cassandra Keyspace. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] + type. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._update_cassandra_keyspace_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + update_throughput_parameters=update_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _migrate_cassandra_keyspace_to_autoscale_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_cassandra_keyspace_to_autoscale_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_migrate_cassandra_keyspace_to_autoscale( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB Cassandra Keyspace from manual throughput to autoscale. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._migrate_cassandra_keyspace_to_autoscale_initial( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _migrate_cassandra_keyspace_to_manual_throughput_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_cassandra_keyspace_to_manual_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_migrate_cassandra_keyspace_to_manual_throughput( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB Cassandra Keyspace from autoscale to manual throughput. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._migrate_cassandra_keyspace_to_manual_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def list_cassandra_tables( + self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any + ) -> AsyncIterable["_models.CassandraTableGetResults"]: + """Lists the Cassandra table under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :return: An iterator like instance of either CassandraTableGetResults or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.CassandraTableGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.CassandraTableListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_cassandra_tables_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("CassandraTableListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get_cassandra_table( + self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any + ) -> _models.CassandraTableGetResults: + """Gets the Cassandra table under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :return: CassandraTableGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.CassandraTableGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.CassandraTableGetResults] = kwargs.pop("cls", None) + + _request = build_get_cassandra_table_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + table_name=table_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("CassandraTableGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_update_cassandra_table_initial( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + table_name: str, + create_update_cassandra_table_parameters: Union[_models.CassandraTableCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_cassandra_table_parameters, (IOBase, bytes)): + _content = create_update_cassandra_table_parameters + else: + _json = self._serialize.body( + create_update_cassandra_table_parameters, "CassandraTableCreateUpdateParameters" + ) + + _request = build_create_update_cassandra_table_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + table_name=table_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_update_cassandra_table( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + table_name: str, + create_update_cassandra_table_parameters: _models.CassandraTableCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.CassandraTableGetResults]: + """Create or update an Azure Cosmos DB Cassandra Table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :param create_update_cassandra_table_parameters: The parameters to provide for the current + Cassandra Table. Required. + :type create_update_cassandra_table_parameters: + ~azure.mgmt.cosmosdb.models.CassandraTableCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either CassandraTableGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.CassandraTableGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_update_cassandra_table( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + table_name: str, + create_update_cassandra_table_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.CassandraTableGetResults]: + """Create or update an Azure Cosmos DB Cassandra Table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :param create_update_cassandra_table_parameters: The parameters to provide for the current + Cassandra Table. Required. + :type create_update_cassandra_table_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either CassandraTableGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.CassandraTableGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_update_cassandra_table( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + table_name: str, + create_update_cassandra_table_parameters: Union[_models.CassandraTableCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.CassandraTableGetResults]: + """Create or update an Azure Cosmos DB Cassandra Table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :param create_update_cassandra_table_parameters: The parameters to provide for the current + Cassandra Table. Is either a CassandraTableCreateUpdateParameters type or a IO[bytes] type. + Required. + :type create_update_cassandra_table_parameters: + ~azure.mgmt.cosmosdb.models.CassandraTableCreateUpdateParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either CassandraTableGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.CassandraTableGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CassandraTableGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_update_cassandra_table_initial( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + table_name=table_name, + create_update_cassandra_table_parameters=create_update_cassandra_table_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("CassandraTableGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.CassandraTableGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.CassandraTableGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_cassandra_table_initial( + self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_cassandra_table_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + table_name=table_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete_cassandra_table( + self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes an existing Azure Cosmos DB Cassandra table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_cassandra_table_initial( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + table_name=table_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace_async + async def get_cassandra_table_throughput( + self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any + ) -> _models.ThroughputSettingsGetResults: + """Gets the RUs per second of the Cassandra table under an existing Azure Cosmos DB database + account with the provided name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :return: ThroughputSettingsGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + + _request = build_get_cassandra_table_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + table_name=table_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _update_cassandra_table_throughput_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + table_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(update_throughput_parameters, (IOBase, bytes)): + _content = update_throughput_parameters + else: + _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") + + _request = build_update_cassandra_table_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + table_name=table_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_update_cassandra_table_throughput( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + table_name: str, + update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Cassandra table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current Cassandra table. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update_cassandra_table_throughput( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + table_name: str, + update_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Cassandra table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current Cassandra table. Required. + :type update_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update_cassandra_table_throughput( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + table_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Cassandra table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current Cassandra table. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] + type. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._update_cassandra_table_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + table_name=table_name, + update_throughput_parameters=update_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _migrate_cassandra_table_to_autoscale_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_cassandra_table_to_autoscale_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + table_name=table_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_migrate_cassandra_table_to_autoscale( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB Cassandra table from manual throughput to autoscale. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._migrate_cassandra_table_to_autoscale_initial( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + table_name=table_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _migrate_cassandra_table_to_manual_throughput_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_cassandra_table_to_manual_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + table_name=table_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_migrate_cassandra_table_to_manual_throughput( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB Cassandra table from autoscale to manual throughput. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._migrate_cassandra_table_to_manual_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + table_name=table_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def list_cassandra_views( + self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any + ) -> AsyncIterable["_models.CassandraViewGetResults"]: + """Lists the Cassandra materialized views under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :return: An iterator like instance of either CassandraViewGetResults or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.CassandraViewGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.CassandraViewListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_cassandra_views_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("CassandraViewListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get_cassandra_view( + self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any + ) -> _models.CassandraViewGetResults: + """Gets the Cassandra view under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param view_name: Cosmos DB view name. Required. + :type view_name: str + :return: CassandraViewGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.CassandraViewGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.CassandraViewGetResults] = kwargs.pop("cls", None) + + _request = build_get_cassandra_view_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + view_name=view_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("CassandraViewGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_update_cassandra_view_initial( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + view_name: str, + create_update_cassandra_view_parameters: Union[_models.CassandraViewCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_cassandra_view_parameters, (IOBase, bytes)): + _content = create_update_cassandra_view_parameters + else: + _json = self._serialize.body(create_update_cassandra_view_parameters, "CassandraViewCreateUpdateParameters") + + _request = build_create_update_cassandra_view_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + view_name=view_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_update_cassandra_view( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + view_name: str, + create_update_cassandra_view_parameters: _models.CassandraViewCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.CassandraViewGetResults]: + """Create or update an Azure Cosmos DB Cassandra View. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param view_name: Cosmos DB view name. Required. + :type view_name: str + :param create_update_cassandra_view_parameters: The parameters to provide for the current + Cassandra View. Required. + :type create_update_cassandra_view_parameters: + ~azure.mgmt.cosmosdb.models.CassandraViewCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either CassandraViewGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.CassandraViewGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_update_cassandra_view( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + view_name: str, + create_update_cassandra_view_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.CassandraViewGetResults]: + """Create or update an Azure Cosmos DB Cassandra View. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param view_name: Cosmos DB view name. Required. + :type view_name: str + :param create_update_cassandra_view_parameters: The parameters to provide for the current + Cassandra View. Required. + :type create_update_cassandra_view_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either CassandraViewGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.CassandraViewGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_update_cassandra_view( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + view_name: str, + create_update_cassandra_view_parameters: Union[_models.CassandraViewCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.CassandraViewGetResults]: + """Create or update an Azure Cosmos DB Cassandra View. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param view_name: Cosmos DB view name. Required. + :type view_name: str + :param create_update_cassandra_view_parameters: The parameters to provide for the current + Cassandra View. Is either a CassandraViewCreateUpdateParameters type or a IO[bytes] type. + Required. + :type create_update_cassandra_view_parameters: + ~azure.mgmt.cosmosdb.models.CassandraViewCreateUpdateParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either CassandraViewGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.CassandraViewGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CassandraViewGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_update_cassandra_view_initial( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + view_name=view_name, + create_update_cassandra_view_parameters=create_update_cassandra_view_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("CassandraViewGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.CassandraViewGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.CassandraViewGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_cassandra_view_initial( + self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_cassandra_view_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + view_name=view_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete_cassandra_view( + self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes an existing Azure Cosmos DB Cassandra view. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param view_name: Cosmos DB view name. Required. + :type view_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_cassandra_view_initial( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + view_name=view_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace_async + async def get_cassandra_view_throughput( + self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any + ) -> _models.ThroughputSettingsGetResults: + """Gets the RUs per second of the Cassandra view under an existing Azure Cosmos DB database + account with the provided name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param view_name: Cosmos DB view name. Required. + :type view_name: str + :return: ThroughputSettingsGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + + _request = build_get_cassandra_view_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + view_name=view_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _update_cassandra_view_throughput_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + view_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(update_throughput_parameters, (IOBase, bytes)): + _content = update_throughput_parameters + else: + _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") + + _request = build_update_cassandra_view_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + view_name=view_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_update_cassandra_view_throughput( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + view_name: str, + update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Cassandra view. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param view_name: Cosmos DB view name. Required. + :type view_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current Cassandra view. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update_cassandra_view_throughput( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + view_name: str, + update_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Cassandra view. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param view_name: Cosmos DB view name. Required. + :type view_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current Cassandra view. Required. + :type update_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update_cassandra_view_throughput( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + view_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Cassandra view. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param view_name: Cosmos DB view name. Required. + :type view_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current Cassandra view. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] + type. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._update_cassandra_view_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + view_name=view_name, + update_throughput_parameters=update_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _migrate_cassandra_view_to_autoscale_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_cassandra_view_to_autoscale_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + view_name=view_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_migrate_cassandra_view_to_autoscale( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB Cassandra view from manual throughput to autoscale. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param view_name: Cosmos DB view name. Required. + :type view_name: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._migrate_cassandra_view_to_autoscale_initial( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + view_name=view_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _migrate_cassandra_view_to_manual_throughput_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_cassandra_view_to_manual_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + view_name=view_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_migrate_cassandra_view_to_manual_throughput( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB Cassandra view from autoscale to manual throughput. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param view_name: Cosmos DB view name. Required. + :type view_name: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._migrate_cassandra_view_to_manual_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + view_name=view_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_chaos_fault_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_chaos_fault_operations.py index 49326419d7c..fc75ea58bb2 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_chaos_fault_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_chaos_fault_operations.py @@ -1,414 +1,414 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling - -from ... import models as _models -from ...operations._chaos_fault_operations import build_enable_disable_request, build_get_request, build_list_request - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class ChaosFaultOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`chaos_fault` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> AsyncIterable["_models.ChaosFaultResource"]: - """List Chaos Faults for CosmosDB account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either ChaosFaultResource or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.ChaosFaultResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ChaosFaultListResponse] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("ChaosFaultListResponse", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - async def _enable_disable_initial( - self, - resource_group_name: str, - account_name: str, - chaos_fault: str, - chaos_fault_request: Union[_models.ChaosFaultResource, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(chaos_fault_request, (IOBase, bytes)): - _content = chaos_fault_request - else: - _json = self._serialize.body(chaos_fault_request, "ChaosFaultResource") - - _request = build_enable_disable_request( - resource_group_name=resource_group_name, - account_name=account_name, - chaos_fault=chaos_fault, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_enable_disable( - self, - resource_group_name: str, - account_name: str, - chaos_fault: str, - chaos_fault_request: _models.ChaosFaultResource, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ChaosFaultResource]: - """Enable, disable Chaos Fault in a CosmosDB account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param chaos_fault: The name of the ChaosFault. Required. - :type chaos_fault: str - :param chaos_fault_request: A request object to enable/disable the chaos fault. Required. - :type chaos_fault_request: ~azure.mgmt.cosmosdb.models.ChaosFaultResource - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ChaosFaultResource or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ChaosFaultResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_enable_disable( - self, - resource_group_name: str, - account_name: str, - chaos_fault: str, - chaos_fault_request: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ChaosFaultResource]: - """Enable, disable Chaos Fault in a CosmosDB account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param chaos_fault: The name of the ChaosFault. Required. - :type chaos_fault: str - :param chaos_fault_request: A request object to enable/disable the chaos fault. Required. - :type chaos_fault_request: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ChaosFaultResource or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ChaosFaultResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_enable_disable( - self, - resource_group_name: str, - account_name: str, - chaos_fault: str, - chaos_fault_request: Union[_models.ChaosFaultResource, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.ChaosFaultResource]: - """Enable, disable Chaos Fault in a CosmosDB account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param chaos_fault: The name of the ChaosFault. Required. - :type chaos_fault: str - :param chaos_fault_request: A request object to enable/disable the chaos fault. Is either a - ChaosFaultResource type or a IO[bytes] type. Required. - :type chaos_fault_request: ~azure.mgmt.cosmosdb.models.ChaosFaultResource or IO[bytes] - :return: An instance of AsyncLROPoller that returns either ChaosFaultResource or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ChaosFaultResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ChaosFaultResource] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._enable_disable_initial( - resource_group_name=resource_group_name, - account_name=account_name, - chaos_fault=chaos_fault, - chaos_fault_request=chaos_fault_request, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ChaosFaultResource", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ChaosFaultResource].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ChaosFaultResource]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @distributed_trace_async - async def get( - self, resource_group_name: str, account_name: str, chaos_fault: str, **kwargs: Any - ) -> _models.ChaosFaultResource: - """Get Chaos Fault for a CosmosdB account for a particular Chaos Fault. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param chaos_fault: The name of the ChaosFault. Required. - :type chaos_fault: str - :return: ChaosFaultResource or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ChaosFaultResource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ChaosFaultResource] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - account_name=account_name, - chaos_fault=chaos_fault, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ChaosFaultResource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ...operations._chaos_fault_operations import build_enable_disable_request, build_get_request, build_list_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class ChaosFaultOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`chaos_fault` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> AsyncIterable["_models.ChaosFaultResource"]: + """List Chaos Faults for CosmosDB account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either ChaosFaultResource or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.ChaosFaultResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ChaosFaultListResponse] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ChaosFaultListResponse", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + async def _enable_disable_initial( + self, + resource_group_name: str, + account_name: str, + chaos_fault: str, + chaos_fault_request: Union[_models.ChaosFaultResource, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(chaos_fault_request, (IOBase, bytes)): + _content = chaos_fault_request + else: + _json = self._serialize.body(chaos_fault_request, "ChaosFaultResource") + + _request = build_enable_disable_request( + resource_group_name=resource_group_name, + account_name=account_name, + chaos_fault=chaos_fault, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_enable_disable( + self, + resource_group_name: str, + account_name: str, + chaos_fault: str, + chaos_fault_request: _models.ChaosFaultResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ChaosFaultResource]: + """Enable, disable Chaos Fault in a CosmosDB account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param chaos_fault: The name of the ChaosFault. Required. + :type chaos_fault: str + :param chaos_fault_request: A request object to enable/disable the chaos fault. Required. + :type chaos_fault_request: ~azure.mgmt.cosmosdb.models.ChaosFaultResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ChaosFaultResource or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ChaosFaultResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_enable_disable( + self, + resource_group_name: str, + account_name: str, + chaos_fault: str, + chaos_fault_request: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ChaosFaultResource]: + """Enable, disable Chaos Fault in a CosmosDB account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param chaos_fault: The name of the ChaosFault. Required. + :type chaos_fault: str + :param chaos_fault_request: A request object to enable/disable the chaos fault. Required. + :type chaos_fault_request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ChaosFaultResource or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ChaosFaultResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_enable_disable( + self, + resource_group_name: str, + account_name: str, + chaos_fault: str, + chaos_fault_request: Union[_models.ChaosFaultResource, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.ChaosFaultResource]: + """Enable, disable Chaos Fault in a CosmosDB account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param chaos_fault: The name of the ChaosFault. Required. + :type chaos_fault: str + :param chaos_fault_request: A request object to enable/disable the chaos fault. Is either a + ChaosFaultResource type or a IO[bytes] type. Required. + :type chaos_fault_request: ~azure.mgmt.cosmosdb.models.ChaosFaultResource or IO[bytes] + :return: An instance of AsyncLROPoller that returns either ChaosFaultResource or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ChaosFaultResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ChaosFaultResource] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._enable_disable_initial( + resource_group_name=resource_group_name, + account_name=account_name, + chaos_fault=chaos_fault, + chaos_fault_request=chaos_fault_request, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ChaosFaultResource", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ChaosFaultResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ChaosFaultResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace_async + async def get( + self, resource_group_name: str, account_name: str, chaos_fault: str, **kwargs: Any + ) -> _models.ChaosFaultResource: + """Get Chaos Fault for a CosmosdB account for a particular Chaos Fault. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param chaos_fault: The name of the ChaosFault. Required. + :type chaos_fault: str + :return: ChaosFaultResource or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ChaosFaultResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ChaosFaultResource] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + account_name=account_name, + chaos_fault=chaos_fault, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ChaosFaultResource", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_collection_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_collection_operations.py index cba46b135c7..1e58e81d93e 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_collection_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_collection_operations.py @@ -1,350 +1,350 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._collection_operations import ( - build_list_metric_definitions_request, - build_list_metrics_request, - build_list_usages_request, -) - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class CollectionOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`collection` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_metrics( - self, - resource_group_name: str, - account_name: str, - database_rid: str, - collection_rid: str, - filter: str, - **kwargs: Any - ) -> AsyncIterable["_models.Metric"]: - """Retrieves the metrics determined by the given filter for the given database account and - collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_rid: Cosmos DB database rid. Required. - :type database_rid: str - :param collection_rid: Cosmos DB collection rid. Required. - :type collection_rid: str - :param filter: An OData filter expression that describes a subset of metrics to return. The - parameters that can be filtered are name.value (name of the metric, can have an or of multiple - names), startTime, endTime, and timeGrain. The supported operator is eq. Required. - :type filter: str - :return: An iterator like instance of either Metric or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.Metric] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MetricListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_metrics_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_rid=database_rid, - collection_rid=collection_rid, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("MetricListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list_usages( - self, - resource_group_name: str, - account_name: str, - database_rid: str, - collection_rid: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.Usage"]: - """Retrieves the usages (most recent storage data) for the given collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_rid: Cosmos DB database rid. Required. - :type database_rid: str - :param collection_rid: Cosmos DB collection rid. Required. - :type collection_rid: str - :param filter: An OData filter expression that describes a subset of usages to return. The - supported parameter is name.value (name of the metric, can have an or of multiple names). - Default value is None. - :type filter: str - :return: An iterator like instance of either Usage or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.Usage] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.UsagesResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_usages_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_rid=database_rid, - collection_rid=collection_rid, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("UsagesResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list_metric_definitions( - self, resource_group_name: str, account_name: str, database_rid: str, collection_rid: str, **kwargs: Any - ) -> AsyncIterable["_models.MetricDefinition"]: - """Retrieves metric definitions for the given collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_rid: Cosmos DB database rid. Required. - :type database_rid: str - :param collection_rid: Cosmos DB collection rid. Required. - :type collection_rid: str - :return: An iterator like instance of either MetricDefinition or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.MetricDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MetricDefinitionsListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_metric_definitions_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_rid=database_rid, - collection_rid=collection_rid, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("MetricDefinitionsListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._collection_operations import ( + build_list_metric_definitions_request, + build_list_metrics_request, + build_list_usages_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class CollectionOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`collection` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_metrics( + self, + resource_group_name: str, + account_name: str, + database_rid: str, + collection_rid: str, + filter: str, + **kwargs: Any + ) -> AsyncIterable["_models.Metric"]: + """Retrieves the metrics determined by the given filter for the given database account and + collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_rid: Cosmos DB database rid. Required. + :type database_rid: str + :param collection_rid: Cosmos DB collection rid. Required. + :type collection_rid: str + :param filter: An OData filter expression that describes a subset of metrics to return. The + parameters that can be filtered are name.value (name of the metric, can have an or of multiple + names), startTime, endTime, and timeGrain. The supported operator is eq. Required. + :type filter: str + :return: An iterator like instance of either Metric or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.Metric] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MetricListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_metrics_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_rid=database_rid, + collection_rid=collection_rid, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("MetricListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_usages( + self, + resource_group_name: str, + account_name: str, + database_rid: str, + collection_rid: str, + filter: Optional[str] = None, + **kwargs: Any + ) -> AsyncIterable["_models.Usage"]: + """Retrieves the usages (most recent storage data) for the given collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_rid: Cosmos DB database rid. Required. + :type database_rid: str + :param collection_rid: Cosmos DB collection rid. Required. + :type collection_rid: str + :param filter: An OData filter expression that describes a subset of usages to return. The + supported parameter is name.value (name of the metric, can have an or of multiple names). + Default value is None. + :type filter: str + :return: An iterator like instance of either Usage or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.Usage] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.UsagesResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_usages_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_rid=database_rid, + collection_rid=collection_rid, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("UsagesResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_metric_definitions( + self, resource_group_name: str, account_name: str, database_rid: str, collection_rid: str, **kwargs: Any + ) -> AsyncIterable["_models.MetricDefinition"]: + """Retrieves metric definitions for the given collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_rid: Cosmos DB database rid. Required. + :type database_rid: str + :param collection_rid: Cosmos DB collection rid. Required. + :type collection_rid: str + :return: An iterator like instance of either MetricDefinition or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.MetricDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MetricDefinitionsListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_metric_definitions_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_rid=database_rid, + collection_rid=collection_rid, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("MetricDefinitionsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_collection_partition_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_collection_partition_operations.py index 8d70df8a1aa..d6146c5c07b 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_collection_partition_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_collection_partition_operations.py @@ -1,257 +1,257 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._collection_partition_operations import build_list_metrics_request, build_list_usages_request - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class CollectionPartitionOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`collection_partition` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_metrics( - self, - resource_group_name: str, - account_name: str, - database_rid: str, - collection_rid: str, - filter: str, - **kwargs: Any - ) -> AsyncIterable["_models.PartitionMetric"]: - """Retrieves the metrics determined by the given filter for the given collection, split by - partition. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_rid: Cosmos DB database rid. Required. - :type database_rid: str - :param collection_rid: Cosmos DB collection rid. Required. - :type collection_rid: str - :param filter: An OData filter expression that describes a subset of metrics to return. The - parameters that can be filtered are name.value (name of the metric, can have an or of multiple - names), startTime, endTime, and timeGrain. The supported operator is eq. Required. - :type filter: str - :return: An iterator like instance of either PartitionMetric or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.PartitionMetric] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.PartitionMetricListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_metrics_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_rid=database_rid, - collection_rid=collection_rid, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PartitionMetricListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list_usages( - self, - resource_group_name: str, - account_name: str, - database_rid: str, - collection_rid: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.PartitionUsage"]: - """Retrieves the usages (most recent storage data) for the given collection, split by partition. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_rid: Cosmos DB database rid. Required. - :type database_rid: str - :param collection_rid: Cosmos DB collection rid. Required. - :type collection_rid: str - :param filter: An OData filter expression that describes a subset of usages to return. The - supported parameter is name.value (name of the metric, can have an or of multiple names). - Default value is None. - :type filter: str - :return: An iterator like instance of either PartitionUsage or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.PartitionUsage] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.PartitionUsagesResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_usages_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_rid=database_rid, - collection_rid=collection_rid, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PartitionUsagesResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._collection_partition_operations import build_list_metrics_request, build_list_usages_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class CollectionPartitionOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`collection_partition` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_metrics( + self, + resource_group_name: str, + account_name: str, + database_rid: str, + collection_rid: str, + filter: str, + **kwargs: Any + ) -> AsyncIterable["_models.PartitionMetric"]: + """Retrieves the metrics determined by the given filter for the given collection, split by + partition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_rid: Cosmos DB database rid. Required. + :type database_rid: str + :param collection_rid: Cosmos DB collection rid. Required. + :type collection_rid: str + :param filter: An OData filter expression that describes a subset of metrics to return. The + parameters that can be filtered are name.value (name of the metric, can have an or of multiple + names), startTime, endTime, and timeGrain. The supported operator is eq. Required. + :type filter: str + :return: An iterator like instance of either PartitionMetric or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.PartitionMetric] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PartitionMetricListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_metrics_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_rid=database_rid, + collection_rid=collection_rid, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PartitionMetricListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_usages( + self, + resource_group_name: str, + account_name: str, + database_rid: str, + collection_rid: str, + filter: Optional[str] = None, + **kwargs: Any + ) -> AsyncIterable["_models.PartitionUsage"]: + """Retrieves the usages (most recent storage data) for the given collection, split by partition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_rid: Cosmos DB database rid. Required. + :type database_rid: str + :param collection_rid: Cosmos DB collection rid. Required. + :type collection_rid: str + :param filter: An OData filter expression that describes a subset of usages to return. The + supported parameter is name.value (name of the metric, can have an or of multiple names). + Default value is None. + :type filter: str + :return: An iterator like instance of either PartitionUsage or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.PartitionUsage] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PartitionUsagesResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_usages_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_rid=database_rid, + collection_rid=collection_rid, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PartitionUsagesResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_collection_partition_region_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_collection_partition_region_operations.py index 429bd0eaeae..e74c836fb53 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_collection_partition_region_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_collection_partition_region_operations.py @@ -1,161 +1,161 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._collection_partition_region_operations import build_list_metrics_request - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class CollectionPartitionRegionOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`collection_partition_region` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_metrics( - self, - resource_group_name: str, - account_name: str, - region: str, - database_rid: str, - collection_rid: str, - filter: str, - **kwargs: Any - ) -> AsyncIterable["_models.PartitionMetric"]: - """Retrieves the metrics determined by the given filter for the given collection and region, split - by partition. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param region: Cosmos DB region, with spaces between words and each word capitalized. Required. - :type region: str - :param database_rid: Cosmos DB database rid. Required. - :type database_rid: str - :param collection_rid: Cosmos DB collection rid. Required. - :type collection_rid: str - :param filter: An OData filter expression that describes a subset of metrics to return. The - parameters that can be filtered are name.value (name of the metric, can have an or of multiple - names), startTime, endTime, and timeGrain. The supported operator is eq. Required. - :type filter: str - :return: An iterator like instance of either PartitionMetric or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.PartitionMetric] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.PartitionMetricListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_metrics_request( - resource_group_name=resource_group_name, - account_name=account_name, - region=region, - database_rid=database_rid, - collection_rid=collection_rid, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PartitionMetricListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._collection_partition_region_operations import build_list_metrics_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class CollectionPartitionRegionOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`collection_partition_region` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_metrics( + self, + resource_group_name: str, + account_name: str, + region: str, + database_rid: str, + collection_rid: str, + filter: str, + **kwargs: Any + ) -> AsyncIterable["_models.PartitionMetric"]: + """Retrieves the metrics determined by the given filter for the given collection and region, split + by partition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param region: Cosmos DB region, with spaces between words and each word capitalized. Required. + :type region: str + :param database_rid: Cosmos DB database rid. Required. + :type database_rid: str + :param collection_rid: Cosmos DB collection rid. Required. + :type collection_rid: str + :param filter: An OData filter expression that describes a subset of metrics to return. The + parameters that can be filtered are name.value (name of the metric, can have an or of multiple + names), startTime, endTime, and timeGrain. The supported operator is eq. Required. + :type filter: str + :return: An iterator like instance of either PartitionMetric or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.PartitionMetric] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PartitionMetricListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_metrics_request( + resource_group_name=resource_group_name, + account_name=account_name, + region=region, + database_rid=database_rid, + collection_rid=collection_rid, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PartitionMetricListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_collection_region_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_collection_region_operations.py index 55b07e5a5f7..2047546baa8 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_collection_region_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_collection_region_operations.py @@ -1,161 +1,161 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._collection_region_operations import build_list_metrics_request - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class CollectionRegionOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`collection_region` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_metrics( - self, - resource_group_name: str, - account_name: str, - region: str, - database_rid: str, - collection_rid: str, - filter: str, - **kwargs: Any - ) -> AsyncIterable["_models.Metric"]: - """Retrieves the metrics determined by the given filter for the given database account, collection - and region. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param region: Cosmos DB region, with spaces between words and each word capitalized. Required. - :type region: str - :param database_rid: Cosmos DB database rid. Required. - :type database_rid: str - :param collection_rid: Cosmos DB collection rid. Required. - :type collection_rid: str - :param filter: An OData filter expression that describes a subset of metrics to return. The - parameters that can be filtered are name.value (name of the metric, can have an or of multiple - names), startTime, endTime, and timeGrain. The supported operator is eq. Required. - :type filter: str - :return: An iterator like instance of either Metric or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.Metric] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MetricListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_metrics_request( - resource_group_name=resource_group_name, - account_name=account_name, - region=region, - database_rid=database_rid, - collection_rid=collection_rid, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("MetricListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._collection_region_operations import build_list_metrics_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class CollectionRegionOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`collection_region` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_metrics( + self, + resource_group_name: str, + account_name: str, + region: str, + database_rid: str, + collection_rid: str, + filter: str, + **kwargs: Any + ) -> AsyncIterable["_models.Metric"]: + """Retrieves the metrics determined by the given filter for the given database account, collection + and region. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param region: Cosmos DB region, with spaces between words and each word capitalized. Required. + :type region: str + :param database_rid: Cosmos DB database rid. Required. + :type database_rid: str + :param collection_rid: Cosmos DB collection rid. Required. + :type collection_rid: str + :param filter: An OData filter expression that describes a subset of metrics to return. The + parameters that can be filtered are name.value (name of the metric, can have an or of multiple + names), startTime, endTime, and timeGrain. The supported operator is eq. Required. + :type filter: str + :return: An iterator like instance of either Metric or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.Metric] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MetricListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_metrics_request( + resource_group_name=resource_group_name, + account_name=account_name, + region=region, + database_rid=database_rid, + collection_rid=collection_rid, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("MetricListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_data_transfer_jobs_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_data_transfer_jobs_operations.py index 8dfbc53c440..58b78d7b91b 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_data_transfer_jobs_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_data_transfer_jobs_operations.py @@ -1,590 +1,590 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, Type, TypeVar, Union, overload -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._data_transfer_jobs_operations import ( - build_cancel_request, - build_complete_request, - build_create_request, - build_get_request, - build_list_by_database_account_request, - build_pause_request, - build_resume_request, -) - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class DataTransferJobsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`data_transfer_jobs` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - async def create( - self, - resource_group_name: str, - account_name: str, - job_name: str, - job_create_parameters: _models.CreateJobRequest, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.DataTransferJobGetResults: - """Creates a Data Transfer Job. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param job_name: Name of the Data Transfer Job. Required. - :type job_name: str - :param job_create_parameters: Required. - :type job_create_parameters: ~azure.mgmt.cosmosdb.models.CreateJobRequest - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: DataTransferJobGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create( - self, - resource_group_name: str, - account_name: str, - job_name: str, - job_create_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.DataTransferJobGetResults: - """Creates a Data Transfer Job. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param job_name: Name of the Data Transfer Job. Required. - :type job_name: str - :param job_create_parameters: Required. - :type job_create_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: DataTransferJobGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create( - self, - resource_group_name: str, - account_name: str, - job_name: str, - job_create_parameters: Union[_models.CreateJobRequest, IO[bytes]], - **kwargs: Any - ) -> _models.DataTransferJobGetResults: - """Creates a Data Transfer Job. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param job_name: Name of the Data Transfer Job. Required. - :type job_name: str - :param job_create_parameters: Is either a CreateJobRequest type or a IO[bytes] type. Required. - :type job_create_parameters: ~azure.mgmt.cosmosdb.models.CreateJobRequest or IO[bytes] - :return: DataTransferJobGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.DataTransferJobGetResults] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(job_create_parameters, (IOBase, bytes)): - _content = job_create_parameters - else: - _json = self._serialize.body(job_create_parameters, "CreateJobRequest") - - _request = build_create_request( - resource_group_name=resource_group_name, - account_name=account_name, - job_name=job_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DataTransferJobGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get( - self, resource_group_name: str, account_name: str, job_name: str, **kwargs: Any - ) -> _models.DataTransferJobGetResults: - """Get a Data Transfer Job. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param job_name: Name of the Data Transfer Job. Required. - :type job_name: str - :return: DataTransferJobGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DataTransferJobGetResults] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - account_name=account_name, - job_name=job_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DataTransferJobGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def pause( - self, resource_group_name: str, account_name: str, job_name: str, **kwargs: Any - ) -> _models.DataTransferJobGetResults: - """Pause a Data Transfer Job. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param job_name: Name of the Data Transfer Job. Required. - :type job_name: str - :return: DataTransferJobGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DataTransferJobGetResults] = kwargs.pop("cls", None) - - _request = build_pause_request( - resource_group_name=resource_group_name, - account_name=account_name, - job_name=job_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DataTransferJobGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def resume( - self, resource_group_name: str, account_name: str, job_name: str, **kwargs: Any - ) -> _models.DataTransferJobGetResults: - """Resumes a Data Transfer Job. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param job_name: Name of the Data Transfer Job. Required. - :type job_name: str - :return: DataTransferJobGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DataTransferJobGetResults] = kwargs.pop("cls", None) - - _request = build_resume_request( - resource_group_name=resource_group_name, - account_name=account_name, - job_name=job_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DataTransferJobGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def cancel( - self, resource_group_name: str, account_name: str, job_name: str, **kwargs: Any - ) -> _models.DataTransferJobGetResults: - """Cancels a Data Transfer Job. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param job_name: Name of the Data Transfer Job. Required. - :type job_name: str - :return: DataTransferJobGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DataTransferJobGetResults] = kwargs.pop("cls", None) - - _request = build_cancel_request( - resource_group_name=resource_group_name, - account_name=account_name, - job_name=job_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DataTransferJobGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def complete( - self, resource_group_name: str, account_name: str, job_name: str, **kwargs: Any - ) -> _models.DataTransferJobGetResults: - """Completes a Data Transfer Online Job. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param job_name: Name of the Data Transfer Job. Required. - :type job_name: str - :return: DataTransferJobGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DataTransferJobGetResults] = kwargs.pop("cls", None) - - _request = build_complete_request( - resource_group_name=resource_group_name, - account_name=account_name, - job_name=job_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DataTransferJobGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_by_database_account( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> AsyncIterable["_models.DataTransferJobGetResults"]: - """Get a list of Data Transfer jobs. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either DataTransferJobGetResults or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.DataTransferJobGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DataTransferJobFeedResults] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_by_database_account_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("DataTransferJobFeedResults", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, Type, TypeVar, Union, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._data_transfer_jobs_operations import ( + build_cancel_request, + build_complete_request, + build_create_request, + build_get_request, + build_list_by_database_account_request, + build_pause_request, + build_resume_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class DataTransferJobsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`data_transfer_jobs` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def create( + self, + resource_group_name: str, + account_name: str, + job_name: str, + job_create_parameters: _models.CreateJobRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.DataTransferJobGetResults: + """Creates a Data Transfer Job. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param job_name: Name of the Data Transfer Job. Required. + :type job_name: str + :param job_create_parameters: Required. + :type job_create_parameters: ~azure.mgmt.cosmosdb.models.CreateJobRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: DataTransferJobGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, + resource_group_name: str, + account_name: str, + job_name: str, + job_create_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.DataTransferJobGetResults: + """Creates a Data Transfer Job. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param job_name: Name of the Data Transfer Job. Required. + :type job_name: str + :param job_create_parameters: Required. + :type job_create_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: DataTransferJobGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create( + self, + resource_group_name: str, + account_name: str, + job_name: str, + job_create_parameters: Union[_models.CreateJobRequest, IO[bytes]], + **kwargs: Any + ) -> _models.DataTransferJobGetResults: + """Creates a Data Transfer Job. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param job_name: Name of the Data Transfer Job. Required. + :type job_name: str + :param job_create_parameters: Is either a CreateJobRequest type or a IO[bytes] type. Required. + :type job_create_parameters: ~azure.mgmt.cosmosdb.models.CreateJobRequest or IO[bytes] + :return: DataTransferJobGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DataTransferJobGetResults] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(job_create_parameters, (IOBase, bytes)): + _content = job_create_parameters + else: + _json = self._serialize.body(job_create_parameters, "CreateJobRequest") + + _request = build_create_request( + resource_group_name=resource_group_name, + account_name=account_name, + job_name=job_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DataTransferJobGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get( + self, resource_group_name: str, account_name: str, job_name: str, **kwargs: Any + ) -> _models.DataTransferJobGetResults: + """Get a Data Transfer Job. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param job_name: Name of the Data Transfer Job. Required. + :type job_name: str + :return: DataTransferJobGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DataTransferJobGetResults] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + account_name=account_name, + job_name=job_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DataTransferJobGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def pause( + self, resource_group_name: str, account_name: str, job_name: str, **kwargs: Any + ) -> _models.DataTransferJobGetResults: + """Pause a Data Transfer Job. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param job_name: Name of the Data Transfer Job. Required. + :type job_name: str + :return: DataTransferJobGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DataTransferJobGetResults] = kwargs.pop("cls", None) + + _request = build_pause_request( + resource_group_name=resource_group_name, + account_name=account_name, + job_name=job_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DataTransferJobGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def resume( + self, resource_group_name: str, account_name: str, job_name: str, **kwargs: Any + ) -> _models.DataTransferJobGetResults: + """Resumes a Data Transfer Job. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param job_name: Name of the Data Transfer Job. Required. + :type job_name: str + :return: DataTransferJobGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DataTransferJobGetResults] = kwargs.pop("cls", None) + + _request = build_resume_request( + resource_group_name=resource_group_name, + account_name=account_name, + job_name=job_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DataTransferJobGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def cancel( + self, resource_group_name: str, account_name: str, job_name: str, **kwargs: Any + ) -> _models.DataTransferJobGetResults: + """Cancels a Data Transfer Job. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param job_name: Name of the Data Transfer Job. Required. + :type job_name: str + :return: DataTransferJobGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DataTransferJobGetResults] = kwargs.pop("cls", None) + + _request = build_cancel_request( + resource_group_name=resource_group_name, + account_name=account_name, + job_name=job_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DataTransferJobGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def complete( + self, resource_group_name: str, account_name: str, job_name: str, **kwargs: Any + ) -> _models.DataTransferJobGetResults: + """Completes a Data Transfer Online Job. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param job_name: Name of the Data Transfer Job. Required. + :type job_name: str + :return: DataTransferJobGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DataTransferJobGetResults] = kwargs.pop("cls", None) + + _request = build_complete_request( + resource_group_name=resource_group_name, + account_name=account_name, + job_name=job_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DataTransferJobGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_by_database_account( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> AsyncIterable["_models.DataTransferJobGetResults"]: + """Get a list of Data Transfer jobs. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either DataTransferJobGetResults or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.DataTransferJobGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DataTransferJobFeedResults] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_database_account_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("DataTransferJobFeedResults", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_database_account_region_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_database_account_region_operations.py index 134000bbc84..5c4d6917bf8 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_database_account_region_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_database_account_region_operations.py @@ -1,147 +1,147 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._database_account_region_operations import build_list_metrics_request - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class DatabaseAccountRegionOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`database_account_region` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_metrics( - self, resource_group_name: str, account_name: str, region: str, filter: str, **kwargs: Any - ) -> AsyncIterable["_models.Metric"]: - """Retrieves the metrics determined by the given filter for the given database account and region. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param region: Cosmos DB region, with spaces between words and each word capitalized. Required. - :type region: str - :param filter: An OData filter expression that describes a subset of metrics to return. The - parameters that can be filtered are name.value (name of the metric, can have an or of multiple - names), startTime, endTime, and timeGrain. The supported operator is eq. Required. - :type filter: str - :return: An iterator like instance of either Metric or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.Metric] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MetricListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_metrics_request( - resource_group_name=resource_group_name, - account_name=account_name, - region=region, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("MetricListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._database_account_region_operations import build_list_metrics_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class DatabaseAccountRegionOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`database_account_region` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_metrics( + self, resource_group_name: str, account_name: str, region: str, filter: str, **kwargs: Any + ) -> AsyncIterable["_models.Metric"]: + """Retrieves the metrics determined by the given filter for the given database account and region. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param region: Cosmos DB region, with spaces between words and each word capitalized. Required. + :type region: str + :param filter: An OData filter expression that describes a subset of metrics to return. The + parameters that can be filtered are name.value (name of the metric, can have an or of multiple + names), startTime, endTime, and timeGrain. The supported operator is eq. Required. + :type filter: str + :return: An iterator like instance of either Metric or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.Metric] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MetricListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_metrics_request( + resource_group_name=resource_group_name, + account_name=account_name, + region=region, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("MetricListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_database_accounts_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_database_accounts_operations.py index b60503e03dd..2007764906f 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_database_accounts_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_database_accounts_operations.py @@ -1,2124 +1,2124 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling - -from ... import models as _models -from ...operations._database_accounts_operations import ( - build_check_name_exists_request, - build_create_or_update_request, - build_delete_request, - build_failover_priority_change_request, - build_get_read_only_keys_request, - build_get_request, - build_list_by_resource_group_request, - build_list_connection_strings_request, - build_list_keys_request, - build_list_metric_definitions_request, - build_list_metrics_request, - build_list_read_only_keys_request, - build_list_request, - build_list_usages_request, - build_offline_region_request, - build_online_region_request, - build_regenerate_key_request, - build_update_request, -) - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class DatabaseAccountsOperations: # pylint: disable=too-many-public-methods - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`database_accounts` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def get( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> _models.DatabaseAccountGetResults: - """Retrieves the properties of an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: DatabaseAccountGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DatabaseAccountGetResults] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DatabaseAccountGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _update_initial( - self, - resource_group_name: str, - account_name: str, - update_parameters: Union[_models.DatabaseAccountUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(update_parameters, (IOBase, bytes)): - _content = update_parameters - else: - _json = self._serialize.body(update_parameters, "DatabaseAccountUpdateParameters") - - _request = build_update_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_update( - self, - resource_group_name: str, - account_name: str, - update_parameters: _models.DatabaseAccountUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.DatabaseAccountGetResults]: - """Updates the properties of an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param update_parameters: The parameters to provide for the current database account. Required. - :type update_parameters: ~azure.mgmt.cosmosdb.models.DatabaseAccountUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either DatabaseAccountGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_update( - self, - resource_group_name: str, - account_name: str, - update_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.DatabaseAccountGetResults]: - """Updates the properties of an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param update_parameters: The parameters to provide for the current database account. Required. - :type update_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either DatabaseAccountGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_update( - self, - resource_group_name: str, - account_name: str, - update_parameters: Union[_models.DatabaseAccountUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.DatabaseAccountGetResults]: - """Updates the properties of an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param update_parameters: The parameters to provide for the current database account. Is either - a DatabaseAccountUpdateParameters type or a IO[bytes] type. Required. - :type update_parameters: ~azure.mgmt.cosmosdb.models.DatabaseAccountUpdateParameters or - IO[bytes] - :return: An instance of AsyncLROPoller that returns either DatabaseAccountGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.DatabaseAccountGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._update_initial( - resource_group_name=resource_group_name, - account_name=account_name, - update_parameters=update_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("DatabaseAccountGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.DatabaseAccountGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.DatabaseAccountGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _create_or_update_initial( - self, - resource_group_name: str, - account_name: str, - create_update_parameters: Union[_models.DatabaseAccountCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_parameters, (IOBase, bytes)): - _content = create_update_parameters - else: - _json = self._serialize.body(create_update_parameters, "DatabaseAccountCreateUpdateParameters") - - _request = build_create_or_update_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_or_update( - self, - resource_group_name: str, - account_name: str, - create_update_parameters: _models.DatabaseAccountCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.DatabaseAccountGetResults]: - """Creates or updates an Azure Cosmos DB database account. The "Update" method is preferred when - performing updates on an account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param create_update_parameters: The parameters to provide for the current database account. - Required. - :type create_update_parameters: - ~azure.mgmt.cosmosdb.models.DatabaseAccountCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either DatabaseAccountGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_or_update( - self, - resource_group_name: str, - account_name: str, - create_update_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.DatabaseAccountGetResults]: - """Creates or updates an Azure Cosmos DB database account. The "Update" method is preferred when - performing updates on an account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param create_update_parameters: The parameters to provide for the current database account. - Required. - :type create_update_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either DatabaseAccountGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_or_update( - self, - resource_group_name: str, - account_name: str, - create_update_parameters: Union[_models.DatabaseAccountCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.DatabaseAccountGetResults]: - """Creates or updates an Azure Cosmos DB database account. The "Update" method is preferred when - performing updates on an account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param create_update_parameters: The parameters to provide for the current database account. Is - either a DatabaseAccountCreateUpdateParameters type or a IO[bytes] type. Required. - :type create_update_parameters: - ~azure.mgmt.cosmosdb.models.DatabaseAccountCreateUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either DatabaseAccountGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.DatabaseAccountGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_or_update_initial( - resource_group_name=resource_group_name, - account_name=account_name, - create_update_parameters=create_update_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("DatabaseAccountGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.DatabaseAccountGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.DatabaseAccountGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _delete_initial(self, resource_group_name: str, account_name: str, **kwargs: Any) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete(self, resource_group_name: str, account_name: str, **kwargs: Any) -> AsyncLROPoller[None]: - """Deletes an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_initial( - resource_group_name=resource_group_name, - account_name=account_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - async def _failover_priority_change_initial( - self, - resource_group_name: str, - account_name: str, - failover_parameters: Union[_models.FailoverPolicies, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(failover_parameters, (IOBase, bytes)): - _content = failover_parameters - else: - _json = self._serialize.body(failover_parameters, "FailoverPolicies") - - _request = build_failover_priority_change_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_failover_priority_change( - self, - resource_group_name: str, - account_name: str, - failover_parameters: _models.FailoverPolicies, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Changes the failover priority for the Azure Cosmos DB database account. A failover priority of - 0 indicates a write region. The maximum value for a failover priority = (total number of - regions - 1). Failover priority values must be unique for each of the regions in which the - database account exists. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param failover_parameters: The new failover policies for the database account. Required. - :type failover_parameters: ~azure.mgmt.cosmosdb.models.FailoverPolicies - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_failover_priority_change( - self, - resource_group_name: str, - account_name: str, - failover_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Changes the failover priority for the Azure Cosmos DB database account. A failover priority of - 0 indicates a write region. The maximum value for a failover priority = (total number of - regions - 1). Failover priority values must be unique for each of the regions in which the - database account exists. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param failover_parameters: The new failover policies for the database account. Required. - :type failover_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_failover_priority_change( - self, - resource_group_name: str, - account_name: str, - failover_parameters: Union[_models.FailoverPolicies, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Changes the failover priority for the Azure Cosmos DB database account. A failover priority of - 0 indicates a write region. The maximum value for a failover priority = (total number of - regions - 1). Failover priority values must be unique for each of the regions in which the - database account exists. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param failover_parameters: The new failover policies for the database account. Is either a - FailoverPolicies type or a IO[bytes] type. Required. - :type failover_parameters: ~azure.mgmt.cosmosdb.models.FailoverPolicies or IO[bytes] - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._failover_priority_change_initial( - resource_group_name=resource_group_name, - account_name=account_name, - failover_parameters=failover_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace - def list(self, **kwargs: Any) -> AsyncIterable["_models.DatabaseAccountGetResults"]: - """Lists all the Azure Cosmos DB database accounts available under the subscription. - - :return: An iterator like instance of either DatabaseAccountGetResults or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DatabaseAccountsListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("DatabaseAccountsListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list_by_resource_group( - self, resource_group_name: str, **kwargs: Any - ) -> AsyncIterable["_models.DatabaseAccountGetResults"]: - """Lists all the Azure Cosmos DB database accounts available under the given resource group. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :return: An iterator like instance of either DatabaseAccountGetResults or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DatabaseAccountsListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_by_resource_group_request( - resource_group_name=resource_group_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("DatabaseAccountsListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def list_keys( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> _models.DatabaseAccountListKeysResult: - """Lists the access keys for the specified Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: DatabaseAccountListKeysResult or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.DatabaseAccountListKeysResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DatabaseAccountListKeysResult] = kwargs.pop("cls", None) - - _request = build_list_keys_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DatabaseAccountListKeysResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def list_connection_strings( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> _models.DatabaseAccountListConnectionStringsResult: - """Lists the connection strings for the specified Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: DatabaseAccountListConnectionStringsResult or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.DatabaseAccountListConnectionStringsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DatabaseAccountListConnectionStringsResult] = kwargs.pop("cls", None) - - _request = build_list_connection_strings_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DatabaseAccountListConnectionStringsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _offline_region_initial( - self, - resource_group_name: str, - account_name: str, - region_parameter_for_offline: Union[_models.RegionForOnlineOffline, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(region_parameter_for_offline, (IOBase, bytes)): - _content = region_parameter_for_offline - else: - _json = self._serialize.body(region_parameter_for_offline, "RegionForOnlineOffline") - - _request = build_offline_region_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_offline_region( - self, - resource_group_name: str, - account_name: str, - region_parameter_for_offline: _models.RegionForOnlineOffline, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Offline the specified region for the specified Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param region_parameter_for_offline: Cosmos DB region to offline for the database account. - Required. - :type region_parameter_for_offline: ~azure.mgmt.cosmosdb.models.RegionForOnlineOffline - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_offline_region( - self, - resource_group_name: str, - account_name: str, - region_parameter_for_offline: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Offline the specified region for the specified Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param region_parameter_for_offline: Cosmos DB region to offline for the database account. - Required. - :type region_parameter_for_offline: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_offline_region( - self, - resource_group_name: str, - account_name: str, - region_parameter_for_offline: Union[_models.RegionForOnlineOffline, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Offline the specified region for the specified Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param region_parameter_for_offline: Cosmos DB region to offline for the database account. Is - either a RegionForOnlineOffline type or a IO[bytes] type. Required. - :type region_parameter_for_offline: ~azure.mgmt.cosmosdb.models.RegionForOnlineOffline or - IO[bytes] - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._offline_region_initial( - resource_group_name=resource_group_name, - account_name=account_name, - region_parameter_for_offline=region_parameter_for_offline, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - async def _online_region_initial( - self, - resource_group_name: str, - account_name: str, - region_parameter_for_online: Union[_models.RegionForOnlineOffline, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(region_parameter_for_online, (IOBase, bytes)): - _content = region_parameter_for_online - else: - _json = self._serialize.body(region_parameter_for_online, "RegionForOnlineOffline") - - _request = build_online_region_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_online_region( - self, - resource_group_name: str, - account_name: str, - region_parameter_for_online: _models.RegionForOnlineOffline, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Online the specified region for the specified Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param region_parameter_for_online: Cosmos DB region to online for the database account. - Required. - :type region_parameter_for_online: ~azure.mgmt.cosmosdb.models.RegionForOnlineOffline - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_online_region( - self, - resource_group_name: str, - account_name: str, - region_parameter_for_online: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Online the specified region for the specified Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param region_parameter_for_online: Cosmos DB region to online for the database account. - Required. - :type region_parameter_for_online: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_online_region( - self, - resource_group_name: str, - account_name: str, - region_parameter_for_online: Union[_models.RegionForOnlineOffline, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Online the specified region for the specified Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param region_parameter_for_online: Cosmos DB region to online for the database account. Is - either a RegionForOnlineOffline type or a IO[bytes] type. Required. - :type region_parameter_for_online: ~azure.mgmt.cosmosdb.models.RegionForOnlineOffline or - IO[bytes] - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._online_region_initial( - resource_group_name=resource_group_name, - account_name=account_name, - region_parameter_for_online=region_parameter_for_online, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace_async - async def get_read_only_keys( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> _models.DatabaseAccountListReadOnlyKeysResult: - """Lists the read-only access keys for the specified Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: DatabaseAccountListReadOnlyKeysResult or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.DatabaseAccountListReadOnlyKeysResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DatabaseAccountListReadOnlyKeysResult] = kwargs.pop("cls", None) - - _request = build_get_read_only_keys_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DatabaseAccountListReadOnlyKeysResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def list_read_only_keys( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> _models.DatabaseAccountListReadOnlyKeysResult: - """Lists the read-only access keys for the specified Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: DatabaseAccountListReadOnlyKeysResult or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.DatabaseAccountListReadOnlyKeysResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DatabaseAccountListReadOnlyKeysResult] = kwargs.pop("cls", None) - - _request = build_list_read_only_keys_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DatabaseAccountListReadOnlyKeysResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _regenerate_key_initial( - self, - resource_group_name: str, - account_name: str, - key_to_regenerate: Union[_models.DatabaseAccountRegenerateKeyParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(key_to_regenerate, (IOBase, bytes)): - _content = key_to_regenerate - else: - _json = self._serialize.body(key_to_regenerate, "DatabaseAccountRegenerateKeyParameters") - - _request = build_regenerate_key_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_regenerate_key( - self, - resource_group_name: str, - account_name: str, - key_to_regenerate: _models.DatabaseAccountRegenerateKeyParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Regenerates an access key for the specified Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param key_to_regenerate: The name of the key to regenerate. Required. - :type key_to_regenerate: ~azure.mgmt.cosmosdb.models.DatabaseAccountRegenerateKeyParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_regenerate_key( - self, - resource_group_name: str, - account_name: str, - key_to_regenerate: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Regenerates an access key for the specified Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param key_to_regenerate: The name of the key to regenerate. Required. - :type key_to_regenerate: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_regenerate_key( - self, - resource_group_name: str, - account_name: str, - key_to_regenerate: Union[_models.DatabaseAccountRegenerateKeyParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Regenerates an access key for the specified Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param key_to_regenerate: The name of the key to regenerate. Is either a - DatabaseAccountRegenerateKeyParameters type or a IO[bytes] type. Required. - :type key_to_regenerate: ~azure.mgmt.cosmosdb.models.DatabaseAccountRegenerateKeyParameters or - IO[bytes] - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._regenerate_key_initial( - resource_group_name=resource_group_name, - account_name=account_name, - key_to_regenerate=key_to_regenerate, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace_async - async def check_name_exists(self, account_name: str, **kwargs: Any) -> bool: - """Checks that the Azure Cosmos DB account name already exists. A valid account name may contain - only lowercase letters, numbers, and the '-' character, and must be between 3 and 50 - characters. - - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: bool or the result of cls(response) - :rtype: bool - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_check_name_exists_request( - account_name=account_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - return 200 <= response.status_code <= 299 - - @distributed_trace - def list_metrics( - self, resource_group_name: str, account_name: str, filter: str, **kwargs: Any - ) -> AsyncIterable["_models.Metric"]: - """Retrieves the metrics determined by the given filter for the given database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param filter: An OData filter expression that describes a subset of metrics to return. The - parameters that can be filtered are name.value (name of the metric, can have an or of multiple - names), startTime, endTime, and timeGrain. The supported operator is eq. Required. - :type filter: str - :return: An iterator like instance of either Metric or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.Metric] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MetricListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_metrics_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("MetricListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list_usages( - self, resource_group_name: str, account_name: str, filter: Optional[str] = None, **kwargs: Any - ) -> AsyncIterable["_models.Usage"]: - """Retrieves the usages (most recent data) for the given database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param filter: An OData filter expression that describes a subset of usages to return. The - supported parameter is name.value (name of the metric, can have an or of multiple names). - Default value is None. - :type filter: str - :return: An iterator like instance of either Usage or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.Usage] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.UsagesResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_usages_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("UsagesResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list_metric_definitions( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> AsyncIterable["_models.MetricDefinition"]: - """Retrieves metric definitions for the given database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either MetricDefinition or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.MetricDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MetricDefinitionsListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_metric_definitions_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("MetricDefinitionsListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ...operations._database_accounts_operations import ( + build_check_name_exists_request, + build_create_or_update_request, + build_delete_request, + build_failover_priority_change_request, + build_get_read_only_keys_request, + build_get_request, + build_list_by_resource_group_request, + build_list_connection_strings_request, + build_list_keys_request, + build_list_metric_definitions_request, + build_list_metrics_request, + build_list_read_only_keys_request, + build_list_request, + build_list_usages_request, + build_offline_region_request, + build_online_region_request, + build_regenerate_key_request, + build_update_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class DatabaseAccountsOperations: # pylint: disable=too-many-public-methods + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`database_accounts` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> _models.DatabaseAccountGetResults: + """Retrieves the properties of an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: DatabaseAccountGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DatabaseAccountGetResults] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DatabaseAccountGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _update_initial( + self, + resource_group_name: str, + account_name: str, + update_parameters: Union[_models.DatabaseAccountUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(update_parameters, (IOBase, bytes)): + _content = update_parameters + else: + _json = self._serialize.body(update_parameters, "DatabaseAccountUpdateParameters") + + _request = build_update_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_update( + self, + resource_group_name: str, + account_name: str, + update_parameters: _models.DatabaseAccountUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DatabaseAccountGetResults]: + """Updates the properties of an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param update_parameters: The parameters to provide for the current database account. Required. + :type update_parameters: ~azure.mgmt.cosmosdb.models.DatabaseAccountUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either DatabaseAccountGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update( + self, + resource_group_name: str, + account_name: str, + update_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DatabaseAccountGetResults]: + """Updates the properties of an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param update_parameters: The parameters to provide for the current database account. Required. + :type update_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either DatabaseAccountGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update( + self, + resource_group_name: str, + account_name: str, + update_parameters: Union[_models.DatabaseAccountUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.DatabaseAccountGetResults]: + """Updates the properties of an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param update_parameters: The parameters to provide for the current database account. Is either + a DatabaseAccountUpdateParameters type or a IO[bytes] type. Required. + :type update_parameters: ~azure.mgmt.cosmosdb.models.DatabaseAccountUpdateParameters or + IO[bytes] + :return: An instance of AsyncLROPoller that returns either DatabaseAccountGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DatabaseAccountGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._update_initial( + resource_group_name=resource_group_name, + account_name=account_name, + update_parameters=update_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("DatabaseAccountGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.DatabaseAccountGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.DatabaseAccountGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _create_or_update_initial( + self, + resource_group_name: str, + account_name: str, + create_update_parameters: Union[_models.DatabaseAccountCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_parameters, (IOBase, bytes)): + _content = create_update_parameters + else: + _json = self._serialize.body(create_update_parameters, "DatabaseAccountCreateUpdateParameters") + + _request = build_create_or_update_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + account_name: str, + create_update_parameters: _models.DatabaseAccountCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DatabaseAccountGetResults]: + """Creates or updates an Azure Cosmos DB database account. The "Update" method is preferred when + performing updates on an account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param create_update_parameters: The parameters to provide for the current database account. + Required. + :type create_update_parameters: + ~azure.mgmt.cosmosdb.models.DatabaseAccountCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either DatabaseAccountGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + account_name: str, + create_update_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DatabaseAccountGetResults]: + """Creates or updates an Azure Cosmos DB database account. The "Update" method is preferred when + performing updates on an account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param create_update_parameters: The parameters to provide for the current database account. + Required. + :type create_update_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either DatabaseAccountGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + account_name: str, + create_update_parameters: Union[_models.DatabaseAccountCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.DatabaseAccountGetResults]: + """Creates or updates an Azure Cosmos DB database account. The "Update" method is preferred when + performing updates on an account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param create_update_parameters: The parameters to provide for the current database account. Is + either a DatabaseAccountCreateUpdateParameters type or a IO[bytes] type. Required. + :type create_update_parameters: + ~azure.mgmt.cosmosdb.models.DatabaseAccountCreateUpdateParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either DatabaseAccountGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DatabaseAccountGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + account_name=account_name, + create_update_parameters=create_update_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("DatabaseAccountGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.DatabaseAccountGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.DatabaseAccountGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_initial(self, resource_group_name: str, account_name: str, **kwargs: Any) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete(self, resource_group_name: str, account_name: str, **kwargs: Any) -> AsyncLROPoller[None]: + """Deletes an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + account_name=account_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + async def _failover_priority_change_initial( + self, + resource_group_name: str, + account_name: str, + failover_parameters: Union[_models.FailoverPolicies, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(failover_parameters, (IOBase, bytes)): + _content = failover_parameters + else: + _json = self._serialize.body(failover_parameters, "FailoverPolicies") + + _request = build_failover_priority_change_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_failover_priority_change( + self, + resource_group_name: str, + account_name: str, + failover_parameters: _models.FailoverPolicies, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Changes the failover priority for the Azure Cosmos DB database account. A failover priority of + 0 indicates a write region. The maximum value for a failover priority = (total number of + regions - 1). Failover priority values must be unique for each of the regions in which the + database account exists. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param failover_parameters: The new failover policies for the database account. Required. + :type failover_parameters: ~azure.mgmt.cosmosdb.models.FailoverPolicies + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_failover_priority_change( + self, + resource_group_name: str, + account_name: str, + failover_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Changes the failover priority for the Azure Cosmos DB database account. A failover priority of + 0 indicates a write region. The maximum value for a failover priority = (total number of + regions - 1). Failover priority values must be unique for each of the regions in which the + database account exists. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param failover_parameters: The new failover policies for the database account. Required. + :type failover_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_failover_priority_change( + self, + resource_group_name: str, + account_name: str, + failover_parameters: Union[_models.FailoverPolicies, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Changes the failover priority for the Azure Cosmos DB database account. A failover priority of + 0 indicates a write region. The maximum value for a failover priority = (total number of + regions - 1). Failover priority values must be unique for each of the regions in which the + database account exists. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param failover_parameters: The new failover policies for the database account. Is either a + FailoverPolicies type or a IO[bytes] type. Required. + :type failover_parameters: ~azure.mgmt.cosmosdb.models.FailoverPolicies or IO[bytes] + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._failover_priority_change_initial( + resource_group_name=resource_group_name, + account_name=account_name, + failover_parameters=failover_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.DatabaseAccountGetResults"]: + """Lists all the Azure Cosmos DB database accounts available under the subscription. + + :return: An iterator like instance of either DatabaseAccountGetResults or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DatabaseAccountsListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("DatabaseAccountsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_resource_group( + self, resource_group_name: str, **kwargs: Any + ) -> AsyncIterable["_models.DatabaseAccountGetResults"]: + """Lists all the Azure Cosmos DB database accounts available under the given resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :return: An iterator like instance of either DatabaseAccountGetResults or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DatabaseAccountsListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("DatabaseAccountsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def list_keys( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> _models.DatabaseAccountListKeysResult: + """Lists the access keys for the specified Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: DatabaseAccountListKeysResult or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.DatabaseAccountListKeysResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DatabaseAccountListKeysResult] = kwargs.pop("cls", None) + + _request = build_list_keys_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DatabaseAccountListKeysResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def list_connection_strings( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> _models.DatabaseAccountListConnectionStringsResult: + """Lists the connection strings for the specified Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: DatabaseAccountListConnectionStringsResult or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.DatabaseAccountListConnectionStringsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DatabaseAccountListConnectionStringsResult] = kwargs.pop("cls", None) + + _request = build_list_connection_strings_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DatabaseAccountListConnectionStringsResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _offline_region_initial( + self, + resource_group_name: str, + account_name: str, + region_parameter_for_offline: Union[_models.RegionForOnlineOffline, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(region_parameter_for_offline, (IOBase, bytes)): + _content = region_parameter_for_offline + else: + _json = self._serialize.body(region_parameter_for_offline, "RegionForOnlineOffline") + + _request = build_offline_region_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_offline_region( + self, + resource_group_name: str, + account_name: str, + region_parameter_for_offline: _models.RegionForOnlineOffline, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Offline the specified region for the specified Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param region_parameter_for_offline: Cosmos DB region to offline for the database account. + Required. + :type region_parameter_for_offline: ~azure.mgmt.cosmosdb.models.RegionForOnlineOffline + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_offline_region( + self, + resource_group_name: str, + account_name: str, + region_parameter_for_offline: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Offline the specified region for the specified Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param region_parameter_for_offline: Cosmos DB region to offline for the database account. + Required. + :type region_parameter_for_offline: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_offline_region( + self, + resource_group_name: str, + account_name: str, + region_parameter_for_offline: Union[_models.RegionForOnlineOffline, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Offline the specified region for the specified Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param region_parameter_for_offline: Cosmos DB region to offline for the database account. Is + either a RegionForOnlineOffline type or a IO[bytes] type. Required. + :type region_parameter_for_offline: ~azure.mgmt.cosmosdb.models.RegionForOnlineOffline or + IO[bytes] + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._offline_region_initial( + resource_group_name=resource_group_name, + account_name=account_name, + region_parameter_for_offline=region_parameter_for_offline, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + async def _online_region_initial( + self, + resource_group_name: str, + account_name: str, + region_parameter_for_online: Union[_models.RegionForOnlineOffline, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(region_parameter_for_online, (IOBase, bytes)): + _content = region_parameter_for_online + else: + _json = self._serialize.body(region_parameter_for_online, "RegionForOnlineOffline") + + _request = build_online_region_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_online_region( + self, + resource_group_name: str, + account_name: str, + region_parameter_for_online: _models.RegionForOnlineOffline, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Online the specified region for the specified Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param region_parameter_for_online: Cosmos DB region to online for the database account. + Required. + :type region_parameter_for_online: ~azure.mgmt.cosmosdb.models.RegionForOnlineOffline + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_online_region( + self, + resource_group_name: str, + account_name: str, + region_parameter_for_online: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Online the specified region for the specified Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param region_parameter_for_online: Cosmos DB region to online for the database account. + Required. + :type region_parameter_for_online: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_online_region( + self, + resource_group_name: str, + account_name: str, + region_parameter_for_online: Union[_models.RegionForOnlineOffline, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Online the specified region for the specified Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param region_parameter_for_online: Cosmos DB region to online for the database account. Is + either a RegionForOnlineOffline type or a IO[bytes] type. Required. + :type region_parameter_for_online: ~azure.mgmt.cosmosdb.models.RegionForOnlineOffline or + IO[bytes] + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._online_region_initial( + resource_group_name=resource_group_name, + account_name=account_name, + region_parameter_for_online=region_parameter_for_online, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace_async + async def get_read_only_keys( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> _models.DatabaseAccountListReadOnlyKeysResult: + """Lists the read-only access keys for the specified Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: DatabaseAccountListReadOnlyKeysResult or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.DatabaseAccountListReadOnlyKeysResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DatabaseAccountListReadOnlyKeysResult] = kwargs.pop("cls", None) + + _request = build_get_read_only_keys_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DatabaseAccountListReadOnlyKeysResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def list_read_only_keys( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> _models.DatabaseAccountListReadOnlyKeysResult: + """Lists the read-only access keys for the specified Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: DatabaseAccountListReadOnlyKeysResult or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.DatabaseAccountListReadOnlyKeysResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DatabaseAccountListReadOnlyKeysResult] = kwargs.pop("cls", None) + + _request = build_list_read_only_keys_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DatabaseAccountListReadOnlyKeysResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _regenerate_key_initial( + self, + resource_group_name: str, + account_name: str, + key_to_regenerate: Union[_models.DatabaseAccountRegenerateKeyParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(key_to_regenerate, (IOBase, bytes)): + _content = key_to_regenerate + else: + _json = self._serialize.body(key_to_regenerate, "DatabaseAccountRegenerateKeyParameters") + + _request = build_regenerate_key_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_regenerate_key( + self, + resource_group_name: str, + account_name: str, + key_to_regenerate: _models.DatabaseAccountRegenerateKeyParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Regenerates an access key for the specified Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param key_to_regenerate: The name of the key to regenerate. Required. + :type key_to_regenerate: ~azure.mgmt.cosmosdb.models.DatabaseAccountRegenerateKeyParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_regenerate_key( + self, + resource_group_name: str, + account_name: str, + key_to_regenerate: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Regenerates an access key for the specified Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param key_to_regenerate: The name of the key to regenerate. Required. + :type key_to_regenerate: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_regenerate_key( + self, + resource_group_name: str, + account_name: str, + key_to_regenerate: Union[_models.DatabaseAccountRegenerateKeyParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Regenerates an access key for the specified Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param key_to_regenerate: The name of the key to regenerate. Is either a + DatabaseAccountRegenerateKeyParameters type or a IO[bytes] type. Required. + :type key_to_regenerate: ~azure.mgmt.cosmosdb.models.DatabaseAccountRegenerateKeyParameters or + IO[bytes] + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._regenerate_key_initial( + resource_group_name=resource_group_name, + account_name=account_name, + key_to_regenerate=key_to_regenerate, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace_async + async def check_name_exists(self, account_name: str, **kwargs: Any) -> bool: + """Checks that the Azure Cosmos DB account name already exists. A valid account name may contain + only lowercase letters, numbers, and the '-' character, and must be between 3 and 50 + characters. + + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: bool or the result of cls(response) + :rtype: bool + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_check_name_exists_request( + account_name=account_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + return 200 <= response.status_code <= 299 + + @distributed_trace + def list_metrics( + self, resource_group_name: str, account_name: str, filter: str, **kwargs: Any + ) -> AsyncIterable["_models.Metric"]: + """Retrieves the metrics determined by the given filter for the given database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param filter: An OData filter expression that describes a subset of metrics to return. The + parameters that can be filtered are name.value (name of the metric, can have an or of multiple + names), startTime, endTime, and timeGrain. The supported operator is eq. Required. + :type filter: str + :return: An iterator like instance of either Metric or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.Metric] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MetricListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_metrics_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("MetricListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_usages( + self, resource_group_name: str, account_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.Usage"]: + """Retrieves the usages (most recent data) for the given database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param filter: An OData filter expression that describes a subset of usages to return. The + supported parameter is name.value (name of the metric, can have an or of multiple names). + Default value is None. + :type filter: str + :return: An iterator like instance of either Usage or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.Usage] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.UsagesResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_usages_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("UsagesResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_metric_definitions( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> AsyncIterable["_models.MetricDefinition"]: + """Retrieves metric definitions for the given database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either MetricDefinition or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.MetricDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MetricDefinitionsListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_metric_definitions_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("MetricDefinitionsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_database_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_database_operations.py index b45bb4b109a..7b1205f4526 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_database_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_database_operations.py @@ -1,334 +1,334 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._database_operations import ( - build_list_metric_definitions_request, - build_list_metrics_request, - build_list_usages_request, -) - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class DatabaseOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`database` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_metrics( - self, resource_group_name: str, account_name: str, database_rid: str, filter: str, **kwargs: Any - ) -> AsyncIterable["_models.Metric"]: - """Retrieves the metrics determined by the given filter for the given database account and - database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_rid: Cosmos DB database rid. Required. - :type database_rid: str - :param filter: An OData filter expression that describes a subset of metrics to return. The - parameters that can be filtered are name.value (name of the metric, can have an or of multiple - names), startTime, endTime, and timeGrain. The supported operator is eq. Required. - :type filter: str - :return: An iterator like instance of either Metric or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.Metric] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MetricListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_metrics_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_rid=database_rid, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("MetricListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list_usages( - self, - resource_group_name: str, - account_name: str, - database_rid: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.Usage"]: - """Retrieves the usages (most recent data) for the given database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_rid: Cosmos DB database rid. Required. - :type database_rid: str - :param filter: An OData filter expression that describes a subset of usages to return. The - supported parameter is name.value (name of the metric, can have an or of multiple names). - Default value is None. - :type filter: str - :return: An iterator like instance of either Usage or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.Usage] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.UsagesResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_usages_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_rid=database_rid, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("UsagesResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list_metric_definitions( - self, resource_group_name: str, account_name: str, database_rid: str, **kwargs: Any - ) -> AsyncIterable["_models.MetricDefinition"]: - """Retrieves metric definitions for the given database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_rid: Cosmos DB database rid. Required. - :type database_rid: str - :return: An iterator like instance of either MetricDefinition or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.MetricDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MetricDefinitionsListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_metric_definitions_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_rid=database_rid, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("MetricDefinitionsListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._database_operations import ( + build_list_metric_definitions_request, + build_list_metrics_request, + build_list_usages_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class DatabaseOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`database` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_metrics( + self, resource_group_name: str, account_name: str, database_rid: str, filter: str, **kwargs: Any + ) -> AsyncIterable["_models.Metric"]: + """Retrieves the metrics determined by the given filter for the given database account and + database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_rid: Cosmos DB database rid. Required. + :type database_rid: str + :param filter: An OData filter expression that describes a subset of metrics to return. The + parameters that can be filtered are name.value (name of the metric, can have an or of multiple + names), startTime, endTime, and timeGrain. The supported operator is eq. Required. + :type filter: str + :return: An iterator like instance of either Metric or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.Metric] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MetricListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_metrics_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_rid=database_rid, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("MetricListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_usages( + self, + resource_group_name: str, + account_name: str, + database_rid: str, + filter: Optional[str] = None, + **kwargs: Any + ) -> AsyncIterable["_models.Usage"]: + """Retrieves the usages (most recent data) for the given database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_rid: Cosmos DB database rid. Required. + :type database_rid: str + :param filter: An OData filter expression that describes a subset of usages to return. The + supported parameter is name.value (name of the metric, can have an or of multiple names). + Default value is None. + :type filter: str + :return: An iterator like instance of either Usage or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.Usage] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.UsagesResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_usages_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_rid=database_rid, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("UsagesResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_metric_definitions( + self, resource_group_name: str, account_name: str, database_rid: str, **kwargs: Any + ) -> AsyncIterable["_models.MetricDefinition"]: + """Retrieves metric definitions for the given database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_rid: Cosmos DB database rid. Required. + :type database_rid: str + :return: An iterator like instance of either MetricDefinition or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.MetricDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MetricDefinitionsListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_metric_definitions_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_rid=database_rid, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("MetricDefinitionsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_graph_resources_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_graph_resources_operations.py index 6178f010a51..61b15d499f0 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_graph_resources_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_graph_resources_operations.py @@ -1,544 +1,544 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling - -from ... import models as _models -from ...operations._graph_resources_operations import ( - build_create_update_graph_request, - build_delete_graph_resource_request, - build_get_graph_request, - build_list_graphs_request, -) - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class GraphResourcesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`graph_resources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_graphs( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> AsyncIterable["_models.GraphResourceGetResults"]: - """Lists the graphs under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either GraphResourceGetResults or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.GraphResourceGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.GraphResourcesListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_graphs_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("GraphResourcesListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get_graph( - self, resource_group_name: str, account_name: str, graph_name: str, **kwargs: Any - ) -> _models.GraphResourceGetResults: - """Gets the Graph resource under an existing Azure Cosmos DB database account with the provided - name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param graph_name: Cosmos DB graph resource name. Required. - :type graph_name: str - :return: GraphResourceGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.GraphResourceGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.GraphResourceGetResults] = kwargs.pop("cls", None) - - _request = build_get_graph_request( - resource_group_name=resource_group_name, - account_name=account_name, - graph_name=graph_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("GraphResourceGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _create_update_graph_initial( - self, - resource_group_name: str, - account_name: str, - graph_name: str, - create_update_graph_parameters: Union[_models.GraphResourceCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_graph_parameters, (IOBase, bytes)): - _content = create_update_graph_parameters - else: - _json = self._serialize.body(create_update_graph_parameters, "GraphResourceCreateUpdateParameters") - - _request = build_create_update_graph_request( - resource_group_name=resource_group_name, - account_name=account_name, - graph_name=graph_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_update_graph( - self, - resource_group_name: str, - account_name: str, - graph_name: str, - create_update_graph_parameters: _models.GraphResourceCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.GraphResourceGetResults]: - """Create or update an Azure Cosmos DB Graph. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param graph_name: Cosmos DB graph resource name. Required. - :type graph_name: str - :param create_update_graph_parameters: The parameters to provide for the current graph. - Required. - :type create_update_graph_parameters: - ~azure.mgmt.cosmosdb.models.GraphResourceCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either GraphResourceGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.GraphResourceGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_update_graph( - self, - resource_group_name: str, - account_name: str, - graph_name: str, - create_update_graph_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.GraphResourceGetResults]: - """Create or update an Azure Cosmos DB Graph. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param graph_name: Cosmos DB graph resource name. Required. - :type graph_name: str - :param create_update_graph_parameters: The parameters to provide for the current graph. - Required. - :type create_update_graph_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either GraphResourceGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.GraphResourceGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_update_graph( - self, - resource_group_name: str, - account_name: str, - graph_name: str, - create_update_graph_parameters: Union[_models.GraphResourceCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.GraphResourceGetResults]: - """Create or update an Azure Cosmos DB Graph. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param graph_name: Cosmos DB graph resource name. Required. - :type graph_name: str - :param create_update_graph_parameters: The parameters to provide for the current graph. Is - either a GraphResourceCreateUpdateParameters type or a IO[bytes] type. Required. - :type create_update_graph_parameters: - ~azure.mgmt.cosmosdb.models.GraphResourceCreateUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either GraphResourceGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.GraphResourceGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.GraphResourceGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_update_graph_initial( - resource_group_name=resource_group_name, - account_name=account_name, - graph_name=graph_name, - create_update_graph_parameters=create_update_graph_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("GraphResourceGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.GraphResourceGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.GraphResourceGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _delete_graph_resource_initial( - self, resource_group_name: str, account_name: str, graph_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_graph_resource_request( - resource_group_name=resource_group_name, - account_name=account_name, - graph_name=graph_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202, 204]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete_graph_resource( - self, resource_group_name: str, account_name: str, graph_name: str, **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes an existing Azure Cosmos DB Graph Resource. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param graph_name: Cosmos DB graph resource name. Required. - :type graph_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_graph_resource_initial( - resource_group_name=resource_group_name, - account_name=account_name, - graph_name=graph_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ...operations._graph_resources_operations import ( + build_create_update_graph_request, + build_delete_graph_resource_request, + build_get_graph_request, + build_list_graphs_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class GraphResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`graph_resources` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_graphs( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> AsyncIterable["_models.GraphResourceGetResults"]: + """Lists the graphs under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either GraphResourceGetResults or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.GraphResourceGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.GraphResourcesListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_graphs_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("GraphResourcesListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get_graph( + self, resource_group_name: str, account_name: str, graph_name: str, **kwargs: Any + ) -> _models.GraphResourceGetResults: + """Gets the Graph resource under an existing Azure Cosmos DB database account with the provided + name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param graph_name: Cosmos DB graph resource name. Required. + :type graph_name: str + :return: GraphResourceGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.GraphResourceGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.GraphResourceGetResults] = kwargs.pop("cls", None) + + _request = build_get_graph_request( + resource_group_name=resource_group_name, + account_name=account_name, + graph_name=graph_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("GraphResourceGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_update_graph_initial( + self, + resource_group_name: str, + account_name: str, + graph_name: str, + create_update_graph_parameters: Union[_models.GraphResourceCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_graph_parameters, (IOBase, bytes)): + _content = create_update_graph_parameters + else: + _json = self._serialize.body(create_update_graph_parameters, "GraphResourceCreateUpdateParameters") + + _request = build_create_update_graph_request( + resource_group_name=resource_group_name, + account_name=account_name, + graph_name=graph_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_update_graph( + self, + resource_group_name: str, + account_name: str, + graph_name: str, + create_update_graph_parameters: _models.GraphResourceCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.GraphResourceGetResults]: + """Create or update an Azure Cosmos DB Graph. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param graph_name: Cosmos DB graph resource name. Required. + :type graph_name: str + :param create_update_graph_parameters: The parameters to provide for the current graph. + Required. + :type create_update_graph_parameters: + ~azure.mgmt.cosmosdb.models.GraphResourceCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either GraphResourceGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.GraphResourceGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_update_graph( + self, + resource_group_name: str, + account_name: str, + graph_name: str, + create_update_graph_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.GraphResourceGetResults]: + """Create or update an Azure Cosmos DB Graph. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param graph_name: Cosmos DB graph resource name. Required. + :type graph_name: str + :param create_update_graph_parameters: The parameters to provide for the current graph. + Required. + :type create_update_graph_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either GraphResourceGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.GraphResourceGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_update_graph( + self, + resource_group_name: str, + account_name: str, + graph_name: str, + create_update_graph_parameters: Union[_models.GraphResourceCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.GraphResourceGetResults]: + """Create or update an Azure Cosmos DB Graph. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param graph_name: Cosmos DB graph resource name. Required. + :type graph_name: str + :param create_update_graph_parameters: The parameters to provide for the current graph. Is + either a GraphResourceCreateUpdateParameters type or a IO[bytes] type. Required. + :type create_update_graph_parameters: + ~azure.mgmt.cosmosdb.models.GraphResourceCreateUpdateParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either GraphResourceGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.GraphResourceGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.GraphResourceGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_update_graph_initial( + resource_group_name=resource_group_name, + account_name=account_name, + graph_name=graph_name, + create_update_graph_parameters=create_update_graph_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("GraphResourceGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.GraphResourceGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.GraphResourceGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_graph_resource_initial( + self, resource_group_name: str, account_name: str, graph_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_graph_resource_request( + resource_group_name=resource_group_name, + account_name=account_name, + graph_name=graph_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete_graph_resource( + self, resource_group_name: str, account_name: str, graph_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes an existing Azure Cosmos DB Graph Resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param graph_name: Cosmos DB graph resource name. Required. + :type graph_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_graph_resource_initial( + resource_group_name=resource_group_name, + account_name=account_name, + graph_name=graph_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_gremlin_resources_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_gremlin_resources_operations.py index 7f4edb35ac3..8763dd96ee7 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_gremlin_resources_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_gremlin_resources_operations.py @@ -1,2351 +1,2351 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling - -from ... import models as _models -from ...operations._gremlin_resources_operations import ( - build_create_update_gremlin_database_request, - build_create_update_gremlin_graph_request, - build_delete_gremlin_database_request, - build_delete_gremlin_graph_request, - build_get_gremlin_database_request, - build_get_gremlin_database_throughput_request, - build_get_gremlin_graph_request, - build_get_gremlin_graph_throughput_request, - build_list_gremlin_databases_request, - build_list_gremlin_graphs_request, - build_migrate_gremlin_database_to_autoscale_request, - build_migrate_gremlin_database_to_manual_throughput_request, - build_migrate_gremlin_graph_to_autoscale_request, - build_migrate_gremlin_graph_to_manual_throughput_request, - build_retrieve_continuous_backup_information_request, - build_update_gremlin_database_throughput_request, - build_update_gremlin_graph_throughput_request, -) - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class GremlinResourcesOperations: # pylint: disable=too-many-public-methods - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`gremlin_resources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_gremlin_databases( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> AsyncIterable["_models.GremlinDatabaseGetResults"]: - """Lists the Gremlin databases under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either GremlinDatabaseGetResults or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.GremlinDatabaseListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_gremlin_databases_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("GremlinDatabaseListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get_gremlin_database( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> _models.GremlinDatabaseGetResults: - """Gets the Gremlin databases under an existing Azure Cosmos DB database account with the provided - name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: GremlinDatabaseGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.GremlinDatabaseGetResults] = kwargs.pop("cls", None) - - _request = build_get_gremlin_database_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("GremlinDatabaseGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _create_update_gremlin_database_initial( - self, - resource_group_name: str, - account_name: str, - database_name: str, - create_update_gremlin_database_parameters: Union[_models.GremlinDatabaseCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_gremlin_database_parameters, (IOBase, bytes)): - _content = create_update_gremlin_database_parameters - else: - _json = self._serialize.body( - create_update_gremlin_database_parameters, "GremlinDatabaseCreateUpdateParameters" - ) - - _request = build_create_update_gremlin_database_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_update_gremlin_database( - self, - resource_group_name: str, - account_name: str, - database_name: str, - create_update_gremlin_database_parameters: _models.GremlinDatabaseCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.GremlinDatabaseGetResults]: - """Create or update an Azure Cosmos DB Gremlin database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param create_update_gremlin_database_parameters: The parameters to provide for the current - Gremlin database. Required. - :type create_update_gremlin_database_parameters: - ~azure.mgmt.cosmosdb.models.GremlinDatabaseCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either GremlinDatabaseGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_update_gremlin_database( - self, - resource_group_name: str, - account_name: str, - database_name: str, - create_update_gremlin_database_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.GremlinDatabaseGetResults]: - """Create or update an Azure Cosmos DB Gremlin database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param create_update_gremlin_database_parameters: The parameters to provide for the current - Gremlin database. Required. - :type create_update_gremlin_database_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either GremlinDatabaseGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_update_gremlin_database( - self, - resource_group_name: str, - account_name: str, - database_name: str, - create_update_gremlin_database_parameters: Union[_models.GremlinDatabaseCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.GremlinDatabaseGetResults]: - """Create or update an Azure Cosmos DB Gremlin database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param create_update_gremlin_database_parameters: The parameters to provide for the current - Gremlin database. Is either a GremlinDatabaseCreateUpdateParameters type or a IO[bytes] type. - Required. - :type create_update_gremlin_database_parameters: - ~azure.mgmt.cosmosdb.models.GremlinDatabaseCreateUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either GremlinDatabaseGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.GremlinDatabaseGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_update_gremlin_database_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - create_update_gremlin_database_parameters=create_update_gremlin_database_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("GremlinDatabaseGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.GremlinDatabaseGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.GremlinDatabaseGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _delete_gremlin_database_initial( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_gremlin_database_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete_gremlin_database( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes an existing Azure Cosmos DB Gremlin database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_gremlin_database_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace_async - async def get_gremlin_database_throughput( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> _models.ThroughputSettingsGetResults: - """Gets the RUs per second of the Gremlin database under an existing Azure Cosmos DB database - account with the provided name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: ThroughputSettingsGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - - _request = build_get_gremlin_database_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _update_gremlin_database_throughput_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(update_throughput_parameters, (IOBase, bytes)): - _content = update_throughput_parameters - else: - _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") - - _request = build_update_gremlin_database_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_update_gremlin_database_throughput( - self, - resource_group_name: str, - account_name: str, - database_name: str, - update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Gremlin database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current Gremlin database. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_update_gremlin_database_throughput( - self, - resource_group_name: str, - account_name: str, - database_name: str, - update_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Gremlin database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current Gremlin database. Required. - :type update_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_update_gremlin_database_throughput( - self, - resource_group_name: str, - account_name: str, - database_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Gremlin database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current Gremlin database. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] - type. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._update_gremlin_database_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - update_throughput_parameters=update_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _migrate_gremlin_database_to_autoscale_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_gremlin_database_to_autoscale_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_migrate_gremlin_database_to_autoscale( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB Gremlin database from manual throughput to autoscale. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._migrate_gremlin_database_to_autoscale_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _migrate_gremlin_database_to_manual_throughput_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_gremlin_database_to_manual_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_migrate_gremlin_database_to_manual_throughput( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB Gremlin database from autoscale to manual throughput. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._migrate_gremlin_database_to_manual_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @distributed_trace - def list_gremlin_graphs( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> AsyncIterable["_models.GremlinGraphGetResults"]: - """Lists the Gremlin graph under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: An iterator like instance of either GremlinGraphGetResults or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.GremlinGraphGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.GremlinGraphListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_gremlin_graphs_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("GremlinGraphListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get_gremlin_graph( - self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any - ) -> _models.GremlinGraphGetResults: - """Gets the Gremlin graph under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param graph_name: Cosmos DB graph name. Required. - :type graph_name: str - :return: GremlinGraphGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.GremlinGraphGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.GremlinGraphGetResults] = kwargs.pop("cls", None) - - _request = build_get_gremlin_graph_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - graph_name=graph_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("GremlinGraphGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _create_update_gremlin_graph_initial( - self, - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - create_update_gremlin_graph_parameters: Union[_models.GremlinGraphCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_gremlin_graph_parameters, (IOBase, bytes)): - _content = create_update_gremlin_graph_parameters - else: - _json = self._serialize.body(create_update_gremlin_graph_parameters, "GremlinGraphCreateUpdateParameters") - - _request = build_create_update_gremlin_graph_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - graph_name=graph_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_update_gremlin_graph( - self, - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - create_update_gremlin_graph_parameters: _models.GremlinGraphCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.GremlinGraphGetResults]: - """Create or update an Azure Cosmos DB Gremlin graph. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param graph_name: Cosmos DB graph name. Required. - :type graph_name: str - :param create_update_gremlin_graph_parameters: The parameters to provide for the current - Gremlin graph. Required. - :type create_update_gremlin_graph_parameters: - ~azure.mgmt.cosmosdb.models.GremlinGraphCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either GremlinGraphGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.GremlinGraphGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_update_gremlin_graph( - self, - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - create_update_gremlin_graph_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.GremlinGraphGetResults]: - """Create or update an Azure Cosmos DB Gremlin graph. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param graph_name: Cosmos DB graph name. Required. - :type graph_name: str - :param create_update_gremlin_graph_parameters: The parameters to provide for the current - Gremlin graph. Required. - :type create_update_gremlin_graph_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either GremlinGraphGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.GremlinGraphGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_update_gremlin_graph( - self, - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - create_update_gremlin_graph_parameters: Union[_models.GremlinGraphCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.GremlinGraphGetResults]: - """Create or update an Azure Cosmos DB Gremlin graph. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param graph_name: Cosmos DB graph name. Required. - :type graph_name: str - :param create_update_gremlin_graph_parameters: The parameters to provide for the current - Gremlin graph. Is either a GremlinGraphCreateUpdateParameters type or a IO[bytes] type. - Required. - :type create_update_gremlin_graph_parameters: - ~azure.mgmt.cosmosdb.models.GremlinGraphCreateUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either GremlinGraphGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.GremlinGraphGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.GremlinGraphGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_update_gremlin_graph_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - graph_name=graph_name, - create_update_gremlin_graph_parameters=create_update_gremlin_graph_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("GremlinGraphGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.GremlinGraphGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.GremlinGraphGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _delete_gremlin_graph_initial( - self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_gremlin_graph_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - graph_name=graph_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete_gremlin_graph( - self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes an existing Azure Cosmos DB Gremlin graph. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param graph_name: Cosmos DB graph name. Required. - :type graph_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_gremlin_graph_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - graph_name=graph_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace_async - async def get_gremlin_graph_throughput( - self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any - ) -> _models.ThroughputSettingsGetResults: - """Gets the Gremlin graph throughput under an existing Azure Cosmos DB database account with the - provided name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param graph_name: Cosmos DB graph name. Required. - :type graph_name: str - :return: ThroughputSettingsGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - - _request = build_get_gremlin_graph_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - graph_name=graph_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _update_gremlin_graph_throughput_initial( - self, - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(update_throughput_parameters, (IOBase, bytes)): - _content = update_throughput_parameters - else: - _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") - - _request = build_update_gremlin_graph_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - graph_name=graph_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_update_gremlin_graph_throughput( - self, - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Gremlin graph. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param graph_name: Cosmos DB graph name. Required. - :type graph_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current Gremlin graph. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_update_gremlin_graph_throughput( - self, - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - update_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Gremlin graph. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param graph_name: Cosmos DB graph name. Required. - :type graph_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current Gremlin graph. Required. - :type update_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_update_gremlin_graph_throughput( - self, - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Gremlin graph. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param graph_name: Cosmos DB graph name. Required. - :type graph_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current Gremlin graph. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] type. - Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._update_gremlin_graph_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - graph_name=graph_name, - update_throughput_parameters=update_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _migrate_gremlin_graph_to_autoscale_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_gremlin_graph_to_autoscale_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - graph_name=graph_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_migrate_gremlin_graph_to_autoscale( - self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB Gremlin graph from manual throughput to autoscale. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param graph_name: Cosmos DB graph name. Required. - :type graph_name: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._migrate_gremlin_graph_to_autoscale_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - graph_name=graph_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _migrate_gremlin_graph_to_manual_throughput_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_gremlin_graph_to_manual_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - graph_name=graph_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_migrate_gremlin_graph_to_manual_throughput( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB Gremlin graph from autoscale to manual throughput. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param graph_name: Cosmos DB graph name. Required. - :type graph_name: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._migrate_gremlin_graph_to_manual_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - graph_name=graph_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _retrieve_continuous_backup_information_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(location, (IOBase, bytes)): - _content = location - else: - _json = self._serialize.body(location, "ContinuousBackupRestoreLocation") - - _request = build_retrieve_continuous_backup_information_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - graph_name=graph_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - location: _models.ContinuousBackupRestoreLocation, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.BackupInformation]: - """Retrieves continuous backup information for a gremlin graph. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param graph_name: Cosmos DB graph name. Required. - :type graph_name: str - :param location: The name of the continuous backup restore location. Required. - :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either BackupInformation or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - location: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.BackupInformation]: - """Retrieves continuous backup information for a gremlin graph. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param graph_name: Cosmos DB graph name. Required. - :type graph_name: str - :param location: The name of the continuous backup restore location. Required. - :type location: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either BackupInformation or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.BackupInformation]: - """Retrieves continuous backup information for a gremlin graph. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param graph_name: Cosmos DB graph name. Required. - :type graph_name: str - :param location: The name of the continuous backup restore location. Is either a - ContinuousBackupRestoreLocation type or a IO[bytes] type. Required. - :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation or IO[bytes] - :return: An instance of AsyncLROPoller that returns either BackupInformation or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.BackupInformation] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._retrieve_continuous_backup_information_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - graph_name=graph_name, - location=location, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("BackupInformation", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.BackupInformation].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.BackupInformation]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ...operations._gremlin_resources_operations import ( + build_create_update_gremlin_database_request, + build_create_update_gremlin_graph_request, + build_delete_gremlin_database_request, + build_delete_gremlin_graph_request, + build_get_gremlin_database_request, + build_get_gremlin_database_throughput_request, + build_get_gremlin_graph_request, + build_get_gremlin_graph_throughput_request, + build_list_gremlin_databases_request, + build_list_gremlin_graphs_request, + build_migrate_gremlin_database_to_autoscale_request, + build_migrate_gremlin_database_to_manual_throughput_request, + build_migrate_gremlin_graph_to_autoscale_request, + build_migrate_gremlin_graph_to_manual_throughput_request, + build_retrieve_continuous_backup_information_request, + build_update_gremlin_database_throughput_request, + build_update_gremlin_graph_throughput_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class GremlinResourcesOperations: # pylint: disable=too-many-public-methods + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`gremlin_resources` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_gremlin_databases( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> AsyncIterable["_models.GremlinDatabaseGetResults"]: + """Lists the Gremlin databases under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either GremlinDatabaseGetResults or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.GremlinDatabaseListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_gremlin_databases_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("GremlinDatabaseListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get_gremlin_database( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> _models.GremlinDatabaseGetResults: + """Gets the Gremlin databases under an existing Azure Cosmos DB database account with the provided + name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: GremlinDatabaseGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.GremlinDatabaseGetResults] = kwargs.pop("cls", None) + + _request = build_get_gremlin_database_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("GremlinDatabaseGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_update_gremlin_database_initial( + self, + resource_group_name: str, + account_name: str, + database_name: str, + create_update_gremlin_database_parameters: Union[_models.GremlinDatabaseCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_gremlin_database_parameters, (IOBase, bytes)): + _content = create_update_gremlin_database_parameters + else: + _json = self._serialize.body( + create_update_gremlin_database_parameters, "GremlinDatabaseCreateUpdateParameters" + ) + + _request = build_create_update_gremlin_database_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_update_gremlin_database( + self, + resource_group_name: str, + account_name: str, + database_name: str, + create_update_gremlin_database_parameters: _models.GremlinDatabaseCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.GremlinDatabaseGetResults]: + """Create or update an Azure Cosmos DB Gremlin database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param create_update_gremlin_database_parameters: The parameters to provide for the current + Gremlin database. Required. + :type create_update_gremlin_database_parameters: + ~azure.mgmt.cosmosdb.models.GremlinDatabaseCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either GremlinDatabaseGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_update_gremlin_database( + self, + resource_group_name: str, + account_name: str, + database_name: str, + create_update_gremlin_database_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.GremlinDatabaseGetResults]: + """Create or update an Azure Cosmos DB Gremlin database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param create_update_gremlin_database_parameters: The parameters to provide for the current + Gremlin database. Required. + :type create_update_gremlin_database_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either GremlinDatabaseGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_update_gremlin_database( + self, + resource_group_name: str, + account_name: str, + database_name: str, + create_update_gremlin_database_parameters: Union[_models.GremlinDatabaseCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.GremlinDatabaseGetResults]: + """Create or update an Azure Cosmos DB Gremlin database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param create_update_gremlin_database_parameters: The parameters to provide for the current + Gremlin database. Is either a GremlinDatabaseCreateUpdateParameters type or a IO[bytes] type. + Required. + :type create_update_gremlin_database_parameters: + ~azure.mgmt.cosmosdb.models.GremlinDatabaseCreateUpdateParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either GremlinDatabaseGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.GremlinDatabaseGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_update_gremlin_database_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + create_update_gremlin_database_parameters=create_update_gremlin_database_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("GremlinDatabaseGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.GremlinDatabaseGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.GremlinDatabaseGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_gremlin_database_initial( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_gremlin_database_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete_gremlin_database( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes an existing Azure Cosmos DB Gremlin database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_gremlin_database_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace_async + async def get_gremlin_database_throughput( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> _models.ThroughputSettingsGetResults: + """Gets the RUs per second of the Gremlin database under an existing Azure Cosmos DB database + account with the provided name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: ThroughputSettingsGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + + _request = build_get_gremlin_database_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _update_gremlin_database_throughput_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(update_throughput_parameters, (IOBase, bytes)): + _content = update_throughput_parameters + else: + _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") + + _request = build_update_gremlin_database_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_update_gremlin_database_throughput( + self, + resource_group_name: str, + account_name: str, + database_name: str, + update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Gremlin database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current Gremlin database. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update_gremlin_database_throughput( + self, + resource_group_name: str, + account_name: str, + database_name: str, + update_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Gremlin database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current Gremlin database. Required. + :type update_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update_gremlin_database_throughput( + self, + resource_group_name: str, + account_name: str, + database_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Gremlin database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current Gremlin database. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] + type. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._update_gremlin_database_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + update_throughput_parameters=update_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _migrate_gremlin_database_to_autoscale_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_gremlin_database_to_autoscale_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_migrate_gremlin_database_to_autoscale( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB Gremlin database from manual throughput to autoscale. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._migrate_gremlin_database_to_autoscale_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _migrate_gremlin_database_to_manual_throughput_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_gremlin_database_to_manual_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_migrate_gremlin_database_to_manual_throughput( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB Gremlin database from autoscale to manual throughput. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._migrate_gremlin_database_to_manual_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def list_gremlin_graphs( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> AsyncIterable["_models.GremlinGraphGetResults"]: + """Lists the Gremlin graph under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: An iterator like instance of either GremlinGraphGetResults or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.GremlinGraphGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.GremlinGraphListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_gremlin_graphs_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("GremlinGraphListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get_gremlin_graph( + self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any + ) -> _models.GremlinGraphGetResults: + """Gets the Gremlin graph under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param graph_name: Cosmos DB graph name. Required. + :type graph_name: str + :return: GremlinGraphGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.GremlinGraphGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.GremlinGraphGetResults] = kwargs.pop("cls", None) + + _request = build_get_gremlin_graph_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + graph_name=graph_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("GremlinGraphGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_update_gremlin_graph_initial( + self, + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + create_update_gremlin_graph_parameters: Union[_models.GremlinGraphCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_gremlin_graph_parameters, (IOBase, bytes)): + _content = create_update_gremlin_graph_parameters + else: + _json = self._serialize.body(create_update_gremlin_graph_parameters, "GremlinGraphCreateUpdateParameters") + + _request = build_create_update_gremlin_graph_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + graph_name=graph_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_update_gremlin_graph( + self, + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + create_update_gremlin_graph_parameters: _models.GremlinGraphCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.GremlinGraphGetResults]: + """Create or update an Azure Cosmos DB Gremlin graph. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param graph_name: Cosmos DB graph name. Required. + :type graph_name: str + :param create_update_gremlin_graph_parameters: The parameters to provide for the current + Gremlin graph. Required. + :type create_update_gremlin_graph_parameters: + ~azure.mgmt.cosmosdb.models.GremlinGraphCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either GremlinGraphGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.GremlinGraphGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_update_gremlin_graph( + self, + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + create_update_gremlin_graph_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.GremlinGraphGetResults]: + """Create or update an Azure Cosmos DB Gremlin graph. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param graph_name: Cosmos DB graph name. Required. + :type graph_name: str + :param create_update_gremlin_graph_parameters: The parameters to provide for the current + Gremlin graph. Required. + :type create_update_gremlin_graph_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either GremlinGraphGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.GremlinGraphGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_update_gremlin_graph( + self, + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + create_update_gremlin_graph_parameters: Union[_models.GremlinGraphCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.GremlinGraphGetResults]: + """Create or update an Azure Cosmos DB Gremlin graph. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param graph_name: Cosmos DB graph name. Required. + :type graph_name: str + :param create_update_gremlin_graph_parameters: The parameters to provide for the current + Gremlin graph. Is either a GremlinGraphCreateUpdateParameters type or a IO[bytes] type. + Required. + :type create_update_gremlin_graph_parameters: + ~azure.mgmt.cosmosdb.models.GremlinGraphCreateUpdateParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either GremlinGraphGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.GremlinGraphGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.GremlinGraphGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_update_gremlin_graph_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + graph_name=graph_name, + create_update_gremlin_graph_parameters=create_update_gremlin_graph_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("GremlinGraphGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.GremlinGraphGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.GremlinGraphGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_gremlin_graph_initial( + self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_gremlin_graph_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + graph_name=graph_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete_gremlin_graph( + self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes an existing Azure Cosmos DB Gremlin graph. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param graph_name: Cosmos DB graph name. Required. + :type graph_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_gremlin_graph_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + graph_name=graph_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace_async + async def get_gremlin_graph_throughput( + self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any + ) -> _models.ThroughputSettingsGetResults: + """Gets the Gremlin graph throughput under an existing Azure Cosmos DB database account with the + provided name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param graph_name: Cosmos DB graph name. Required. + :type graph_name: str + :return: ThroughputSettingsGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + + _request = build_get_gremlin_graph_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + graph_name=graph_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _update_gremlin_graph_throughput_initial( + self, + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(update_throughput_parameters, (IOBase, bytes)): + _content = update_throughput_parameters + else: + _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") + + _request = build_update_gremlin_graph_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + graph_name=graph_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_update_gremlin_graph_throughput( + self, + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Gremlin graph. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param graph_name: Cosmos DB graph name. Required. + :type graph_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current Gremlin graph. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update_gremlin_graph_throughput( + self, + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + update_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Gremlin graph. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param graph_name: Cosmos DB graph name. Required. + :type graph_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current Gremlin graph. Required. + :type update_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update_gremlin_graph_throughput( + self, + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Gremlin graph. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param graph_name: Cosmos DB graph name. Required. + :type graph_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current Gremlin graph. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] type. + Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._update_gremlin_graph_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + graph_name=graph_name, + update_throughput_parameters=update_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _migrate_gremlin_graph_to_autoscale_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_gremlin_graph_to_autoscale_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + graph_name=graph_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_migrate_gremlin_graph_to_autoscale( + self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB Gremlin graph from manual throughput to autoscale. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param graph_name: Cosmos DB graph name. Required. + :type graph_name: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._migrate_gremlin_graph_to_autoscale_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + graph_name=graph_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _migrate_gremlin_graph_to_manual_throughput_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_gremlin_graph_to_manual_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + graph_name=graph_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_migrate_gremlin_graph_to_manual_throughput( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB Gremlin graph from autoscale to manual throughput. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param graph_name: Cosmos DB graph name. Required. + :type graph_name: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._migrate_gremlin_graph_to_manual_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + graph_name=graph_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _retrieve_continuous_backup_information_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(location, (IOBase, bytes)): + _content = location + else: + _json = self._serialize.body(location, "ContinuousBackupRestoreLocation") + + _request = build_retrieve_continuous_backup_information_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + graph_name=graph_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + location: _models.ContinuousBackupRestoreLocation, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.BackupInformation]: + """Retrieves continuous backup information for a gremlin graph. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param graph_name: Cosmos DB graph name. Required. + :type graph_name: str + :param location: The name of the continuous backup restore location. Required. + :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either BackupInformation or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + location: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.BackupInformation]: + """Retrieves continuous backup information for a gremlin graph. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param graph_name: Cosmos DB graph name. Required. + :type graph_name: str + :param location: The name of the continuous backup restore location. Required. + :type location: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either BackupInformation or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.BackupInformation]: + """Retrieves continuous backup information for a gremlin graph. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param graph_name: Cosmos DB graph name. Required. + :type graph_name: str + :param location: The name of the continuous backup restore location. Is either a + ContinuousBackupRestoreLocation type or a IO[bytes] type. Required. + :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation or IO[bytes] + :return: An instance of AsyncLROPoller that returns either BackupInformation or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.BackupInformation] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._retrieve_continuous_backup_information_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + graph_name=graph_name, + location=location, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("BackupInformation", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.BackupInformation].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.BackupInformation]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_locations_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_locations_operations.py index 8755c0dbb7e..dfcc88306b6 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_locations_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_locations_operations.py @@ -1,183 +1,183 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._locations_operations import build_get_request, build_list_request - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class LocationsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`locations` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list(self, **kwargs: Any) -> AsyncIterable["_models.LocationGetResult"]: - """List Cosmos DB locations and their properties. - - :return: An iterator like instance of either LocationGetResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.LocationGetResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.LocationListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("LocationListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get(self, location: str, **kwargs: Any) -> _models.LocationGetResult: - """Get the properties of an existing Cosmos DB location. - - :param location: Cosmos DB region, with spaces between words and each word capitalized. - Required. - :type location: str - :return: LocationGetResult or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.LocationGetResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.LocationGetResult] = kwargs.pop("cls", None) - - _request = build_get_request( - location=location, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("LocationGetResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._locations_operations import build_get_request, build_list_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class LocationsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`locations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.LocationGetResult"]: + """List Cosmos DB locations and their properties. + + :return: An iterator like instance of either LocationGetResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.LocationGetResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.LocationListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("LocationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get(self, location: str, **kwargs: Any) -> _models.LocationGetResult: + """Get the properties of an existing Cosmos DB location. + + :param location: Cosmos DB region, with spaces between words and each word capitalized. + Required. + :type location: str + :return: LocationGetResult or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.LocationGetResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.LocationGetResult] = kwargs.pop("cls", None) + + _request = build_get_request( + location=location, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("LocationGetResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_mongo_db_resources_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_mongo_db_resources_operations.py index 2615333d517..07e7de4201c 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_mongo_db_resources_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_mongo_db_resources_operations.py @@ -1,4666 +1,4666 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling - -from ... import models as _models -from ...operations._mongo_db_resources_operations import ( - build_create_update_mongo_db_collection_request, - build_create_update_mongo_db_database_request, - build_create_update_mongo_role_definition_request, - build_create_update_mongo_user_definition_request, - build_delete_mongo_db_collection_request, - build_delete_mongo_db_database_request, - build_delete_mongo_role_definition_request, - build_delete_mongo_user_definition_request, - build_get_mongo_db_collection_request, - build_get_mongo_db_collection_throughput_request, - build_get_mongo_db_database_request, - build_get_mongo_db_database_throughput_request, - build_get_mongo_role_definition_request, - build_get_mongo_user_definition_request, - build_list_mongo_db_collection_partition_merge_request, - build_list_mongo_db_collections_request, - build_list_mongo_db_databases_request, - build_list_mongo_role_definitions_request, - build_list_mongo_user_definitions_request, - build_migrate_mongo_db_collection_to_autoscale_request, - build_migrate_mongo_db_collection_to_manual_throughput_request, - build_migrate_mongo_db_database_to_autoscale_request, - build_migrate_mongo_db_database_to_manual_throughput_request, - build_mongo_db_container_redistribute_throughput_request, - build_mongo_db_container_retrieve_throughput_distribution_request, - build_mongo_db_database_partition_merge_request, - build_mongo_db_database_redistribute_throughput_request, - build_mongo_db_database_retrieve_throughput_distribution_request, - build_retrieve_continuous_backup_information_request, - build_update_mongo_db_collection_throughput_request, - build_update_mongo_db_database_throughput_request, -) - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class MongoDBResourcesOperations: # pylint: disable=too-many-public-methods - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`mongo_db_resources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_mongo_db_databases( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> AsyncIterable["_models.MongoDBDatabaseGetResults"]: - """Lists the MongoDB databases under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either MongoDBDatabaseGetResults or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MongoDBDatabaseListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_mongo_db_databases_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("MongoDBDatabaseListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get_mongo_db_database( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> _models.MongoDBDatabaseGetResults: - """Gets the MongoDB databases under an existing Azure Cosmos DB database account with the provided - name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: MongoDBDatabaseGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MongoDBDatabaseGetResults] = kwargs.pop("cls", None) - - _request = build_get_mongo_db_database_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("MongoDBDatabaseGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _create_update_mongo_db_database_initial( - self, - resource_group_name: str, - account_name: str, - database_name: str, - create_update_mongo_db_database_parameters: Union[_models.MongoDBDatabaseCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_mongo_db_database_parameters, (IOBase, bytes)): - _content = create_update_mongo_db_database_parameters - else: - _json = self._serialize.body( - create_update_mongo_db_database_parameters, "MongoDBDatabaseCreateUpdateParameters" - ) - - _request = build_create_update_mongo_db_database_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_update_mongo_db_database( - self, - resource_group_name: str, - account_name: str, - database_name: str, - create_update_mongo_db_database_parameters: _models.MongoDBDatabaseCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.MongoDBDatabaseGetResults]: - """Create or updates Azure Cosmos DB MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param create_update_mongo_db_database_parameters: The parameters to provide for the current - MongoDB database. Required. - :type create_update_mongo_db_database_parameters: - ~azure.mgmt.cosmosdb.models.MongoDBDatabaseCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either MongoDBDatabaseGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_update_mongo_db_database( - self, - resource_group_name: str, - account_name: str, - database_name: str, - create_update_mongo_db_database_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.MongoDBDatabaseGetResults]: - """Create or updates Azure Cosmos DB MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param create_update_mongo_db_database_parameters: The parameters to provide for the current - MongoDB database. Required. - :type create_update_mongo_db_database_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either MongoDBDatabaseGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_update_mongo_db_database( - self, - resource_group_name: str, - account_name: str, - database_name: str, - create_update_mongo_db_database_parameters: Union[_models.MongoDBDatabaseCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.MongoDBDatabaseGetResults]: - """Create or updates Azure Cosmos DB MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param create_update_mongo_db_database_parameters: The parameters to provide for the current - MongoDB database. Is either a MongoDBDatabaseCreateUpdateParameters type or a IO[bytes] type. - Required. - :type create_update_mongo_db_database_parameters: - ~azure.mgmt.cosmosdb.models.MongoDBDatabaseCreateUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either MongoDBDatabaseGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.MongoDBDatabaseGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_update_mongo_db_database_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - create_update_mongo_db_database_parameters=create_update_mongo_db_database_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("MongoDBDatabaseGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.MongoDBDatabaseGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.MongoDBDatabaseGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _delete_mongo_db_database_initial( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_mongo_db_database_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete_mongo_db_database( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes an existing Azure Cosmos DB MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_mongo_db_database_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace_async - async def get_mongo_db_database_throughput( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> _models.ThroughputSettingsGetResults: - """Gets the RUs per second of the MongoDB database under an existing Azure Cosmos DB database - account with the provided name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: ThroughputSettingsGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - - _request = build_get_mongo_db_database_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _update_mongo_db_database_throughput_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(update_throughput_parameters, (IOBase, bytes)): - _content = update_throughput_parameters - else: - _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") - - _request = build_update_mongo_db_database_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_update_mongo_db_database_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of the an Azure Cosmos DB MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current MongoDB database. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_update_mongo_db_database_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - update_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of the an Azure Cosmos DB MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current MongoDB database. Required. - :type update_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_update_mongo_db_database_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of the an Azure Cosmos DB MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current MongoDB database. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] - type. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._update_mongo_db_database_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - update_throughput_parameters=update_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _migrate_mongo_db_database_to_autoscale_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_mongo_db_database_to_autoscale_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_migrate_mongo_db_database_to_autoscale( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB MongoDB database from manual throughput to autoscale. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._migrate_mongo_db_database_to_autoscale_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _migrate_mongo_db_database_to_manual_throughput_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_mongo_db_database_to_manual_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_migrate_mongo_db_database_to_manual_throughput( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB MongoDB database from autoscale to manual throughput. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._migrate_mongo_db_database_to_manual_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _mongo_db_database_retrieve_throughput_distribution_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(retrieve_throughput_parameters, (IOBase, bytes)): - _content = retrieve_throughput_parameters - else: - _json = self._serialize.body(retrieve_throughput_parameters, "RetrieveThroughputParameters") - - _request = build_mongo_db_database_retrieve_throughput_distribution_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_mongo_db_database_retrieve_throughput_distribution( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - retrieve_throughput_parameters: _models.RetrieveThroughputParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Retrieve throughput distribution for an Azure Cosmos DB MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput - distribution for the current MongoDB database. Required. - :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionThroughputInfoResult or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_mongo_db_database_retrieve_throughput_distribution( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - retrieve_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Retrieve throughput distribution for an Azure Cosmos DB MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput - distribution for the current MongoDB database. Required. - :type retrieve_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionThroughputInfoResult or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_mongo_db_database_retrieve_throughput_distribution( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Retrieve throughput distribution for an Azure Cosmos DB MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput - distribution for the current MongoDB database. Is either a RetrieveThroughputParameters type or - a IO[bytes] type. Required. - :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters - or IO[bytes] - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionThroughputInfoResult or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._mongo_db_database_retrieve_throughput_distribution_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - retrieve_throughput_parameters=retrieve_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _mongo_db_database_redistribute_throughput_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(redistribute_throughput_parameters, (IOBase, bytes)): - _content = redistribute_throughput_parameters - else: - _json = self._serialize.body(redistribute_throughput_parameters, "RedistributeThroughputParameters") - - _request = build_mongo_db_database_redistribute_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_mongo_db_database_redistribute_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - redistribute_throughput_parameters: _models.RedistributeThroughputParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Redistribute throughput for an Azure Cosmos DB MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param redistribute_throughput_parameters: The parameters to provide for redistributing - throughput for the current MongoDB database. Required. - :type redistribute_throughput_parameters: - ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionThroughputInfoResult or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_mongo_db_database_redistribute_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - redistribute_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Redistribute throughput for an Azure Cosmos DB MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param redistribute_throughput_parameters: The parameters to provide for redistributing - throughput for the current MongoDB database. Required. - :type redistribute_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionThroughputInfoResult or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_mongo_db_database_redistribute_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Redistribute throughput for an Azure Cosmos DB MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param redistribute_throughput_parameters: The parameters to provide for redistributing - throughput for the current MongoDB database. Is either a RedistributeThroughputParameters type - or a IO[bytes] type. Required. - :type redistribute_throughput_parameters: - ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionThroughputInfoResult or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._mongo_db_database_redistribute_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - redistribute_throughput_parameters=redistribute_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _mongo_db_container_retrieve_throughput_distribution_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(retrieve_throughput_parameters, (IOBase, bytes)): - _content = retrieve_throughput_parameters - else: - _json = self._serialize.body(retrieve_throughput_parameters, "RetrieveThroughputParameters") - - _request = build_mongo_db_container_retrieve_throughput_distribution_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_mongo_db_container_retrieve_throughput_distribution( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - retrieve_throughput_parameters: _models.RetrieveThroughputParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Retrieve throughput distribution for an Azure Cosmos DB MongoDB container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput - distribution for the current MongoDB container. Required. - :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionThroughputInfoResult or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_mongo_db_container_retrieve_throughput_distribution( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - retrieve_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Retrieve throughput distribution for an Azure Cosmos DB MongoDB container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput - distribution for the current MongoDB container. Required. - :type retrieve_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionThroughputInfoResult or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_mongo_db_container_retrieve_throughput_distribution( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Retrieve throughput distribution for an Azure Cosmos DB MongoDB container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput - distribution for the current MongoDB container. Is either a RetrieveThroughputParameters type - or a IO[bytes] type. Required. - :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters - or IO[bytes] - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionThroughputInfoResult or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._mongo_db_container_retrieve_throughput_distribution_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - retrieve_throughput_parameters=retrieve_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _mongo_db_container_redistribute_throughput_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(redistribute_throughput_parameters, (IOBase, bytes)): - _content = redistribute_throughput_parameters - else: - _json = self._serialize.body(redistribute_throughput_parameters, "RedistributeThroughputParameters") - - _request = build_mongo_db_container_redistribute_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_mongo_db_container_redistribute_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - redistribute_throughput_parameters: _models.RedistributeThroughputParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Redistribute throughput for an Azure Cosmos DB MongoDB container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param redistribute_throughput_parameters: The parameters to provide for redistributing - throughput for the current MongoDB container. Required. - :type redistribute_throughput_parameters: - ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionThroughputInfoResult or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_mongo_db_container_redistribute_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - redistribute_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Redistribute throughput for an Azure Cosmos DB MongoDB container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param redistribute_throughput_parameters: The parameters to provide for redistributing - throughput for the current MongoDB container. Required. - :type redistribute_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionThroughputInfoResult or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_mongo_db_container_redistribute_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Redistribute throughput for an Azure Cosmos DB MongoDB container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param redistribute_throughput_parameters: The parameters to provide for redistributing - throughput for the current MongoDB container. Is either a RedistributeThroughputParameters type - or a IO[bytes] type. Required. - :type redistribute_throughput_parameters: - ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionThroughputInfoResult or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._mongo_db_container_redistribute_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - redistribute_throughput_parameters=redistribute_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @distributed_trace - def list_mongo_db_collections( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> AsyncIterable["_models.MongoDBCollectionGetResults"]: - """Lists the MongoDB collection under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: An iterator like instance of either MongoDBCollectionGetResults or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.MongoDBCollectionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MongoDBCollectionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_mongo_db_collections_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("MongoDBCollectionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get_mongo_db_collection( - self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any - ) -> _models.MongoDBCollectionGetResults: - """Gets the MongoDB collection under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :return: MongoDBCollectionGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.MongoDBCollectionGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MongoDBCollectionGetResults] = kwargs.pop("cls", None) - - _request = build_get_mongo_db_collection_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("MongoDBCollectionGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _create_update_mongo_db_collection_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - create_update_mongo_db_collection_parameters: Union[_models.MongoDBCollectionCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_mongo_db_collection_parameters, (IOBase, bytes)): - _content = create_update_mongo_db_collection_parameters - else: - _json = self._serialize.body( - create_update_mongo_db_collection_parameters, "MongoDBCollectionCreateUpdateParameters" - ) - - _request = build_create_update_mongo_db_collection_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_update_mongo_db_collection( - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - create_update_mongo_db_collection_parameters: _models.MongoDBCollectionCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.MongoDBCollectionGetResults]: - """Create or update an Azure Cosmos DB MongoDB Collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param create_update_mongo_db_collection_parameters: The parameters to provide for the current - MongoDB Collection. Required. - :type create_update_mongo_db_collection_parameters: - ~azure.mgmt.cosmosdb.models.MongoDBCollectionCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either MongoDBCollectionGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoDBCollectionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_update_mongo_db_collection( - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - create_update_mongo_db_collection_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.MongoDBCollectionGetResults]: - """Create or update an Azure Cosmos DB MongoDB Collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param create_update_mongo_db_collection_parameters: The parameters to provide for the current - MongoDB Collection. Required. - :type create_update_mongo_db_collection_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either MongoDBCollectionGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoDBCollectionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_update_mongo_db_collection( - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - create_update_mongo_db_collection_parameters: Union[_models.MongoDBCollectionCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.MongoDBCollectionGetResults]: - """Create or update an Azure Cosmos DB MongoDB Collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param create_update_mongo_db_collection_parameters: The parameters to provide for the current - MongoDB Collection. Is either a MongoDBCollectionCreateUpdateParameters type or a IO[bytes] - type. Required. - :type create_update_mongo_db_collection_parameters: - ~azure.mgmt.cosmosdb.models.MongoDBCollectionCreateUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either MongoDBCollectionGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoDBCollectionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.MongoDBCollectionGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_update_mongo_db_collection_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - create_update_mongo_db_collection_parameters=create_update_mongo_db_collection_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("MongoDBCollectionGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.MongoDBCollectionGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.MongoDBCollectionGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _delete_mongo_db_collection_initial( - self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_mongo_db_collection_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete_mongo_db_collection( - self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes an existing Azure Cosmos DB MongoDB Collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_mongo_db_collection_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - async def _mongo_db_database_partition_merge_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - merge_parameters: Union[_models.MergeParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(merge_parameters, (IOBase, bytes)): - _content = merge_parameters - else: - _json = self._serialize.body(merge_parameters, "MergeParameters") - - _request = build_mongo_db_database_partition_merge_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_mongo_db_database_partition_merge( - self, - resource_group_name: str, - account_name: str, - database_name: str, - merge_parameters: _models.MergeParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]: - """Merges the partitions of a MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param merge_parameters: The parameters for the merge operation. Required. - :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionStorageInfoCollection or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_mongo_db_database_partition_merge( - self, - resource_group_name: str, - account_name: str, - database_name: str, - merge_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]: - """Merges the partitions of a MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param merge_parameters: The parameters for the merge operation. Required. - :type merge_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionStorageInfoCollection or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_mongo_db_database_partition_merge( - self, - resource_group_name: str, - account_name: str, - database_name: str, - merge_parameters: Union[_models.MergeParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]: - """Merges the partitions of a MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param merge_parameters: The parameters for the merge operation. Is either a MergeParameters - type or a IO[bytes] type. Required. - :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionStorageInfoCollection or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PhysicalPartitionStorageInfoCollection] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._mongo_db_database_partition_merge_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - merge_parameters=merge_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("PhysicalPartitionStorageInfoCollection", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _list_mongo_db_collection_partition_merge_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - merge_parameters: Union[_models.MergeParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(merge_parameters, (IOBase, bytes)): - _content = merge_parameters - else: - _json = self._serialize.body(merge_parameters, "MergeParameters") - - _request = build_list_mongo_db_collection_partition_merge_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_list_mongo_db_collection_partition_merge( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - merge_parameters: _models.MergeParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]: - """Merges the partitions of a MongoDB Collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param merge_parameters: The parameters for the merge operation. Required. - :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionStorageInfoCollection or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_list_mongo_db_collection_partition_merge( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - merge_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]: - """Merges the partitions of a MongoDB Collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param merge_parameters: The parameters for the merge operation. Required. - :type merge_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionStorageInfoCollection or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_list_mongo_db_collection_partition_merge( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - merge_parameters: Union[_models.MergeParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]: - """Merges the partitions of a MongoDB Collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param merge_parameters: The parameters for the merge operation. Is either a MergeParameters - type or a IO[bytes] type. Required. - :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionStorageInfoCollection or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PhysicalPartitionStorageInfoCollection] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._list_mongo_db_collection_partition_merge_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - merge_parameters=merge_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("PhysicalPartitionStorageInfoCollection", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @distributed_trace_async - async def get_mongo_db_collection_throughput( - self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any - ) -> _models.ThroughputSettingsGetResults: - """Gets the RUs per second of the MongoDB collection under an existing Azure Cosmos DB database - account with the provided name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :return: ThroughputSettingsGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - - _request = build_get_mongo_db_collection_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _update_mongo_db_collection_throughput_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(update_throughput_parameters, (IOBase, bytes)): - _content = update_throughput_parameters - else: - _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") - - _request = build_update_mongo_db_collection_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_update_mongo_db_collection_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Update the RUs per second of an Azure Cosmos DB MongoDB collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current MongoDB collection. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_update_mongo_db_collection_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - update_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Update the RUs per second of an Azure Cosmos DB MongoDB collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current MongoDB collection. Required. - :type update_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_update_mongo_db_collection_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Update the RUs per second of an Azure Cosmos DB MongoDB collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current MongoDB collection. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] - type. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._update_mongo_db_collection_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - update_throughput_parameters=update_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _migrate_mongo_db_collection_to_autoscale_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_mongo_db_collection_to_autoscale_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_migrate_mongo_db_collection_to_autoscale( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB MongoDB collection from manual throughput to autoscale. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._migrate_mongo_db_collection_to_autoscale_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _migrate_mongo_db_collection_to_manual_throughput_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_mongo_db_collection_to_manual_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_migrate_mongo_db_collection_to_manual_throughput( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB MongoDB collection from autoscale to manual throughput. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._migrate_mongo_db_collection_to_manual_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @distributed_trace_async - async def get_mongo_role_definition( - self, mongo_role_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any - ) -> _models.MongoRoleDefinitionGetResults: - """Retrieves the properties of an existing Azure Cosmos DB Mongo Role Definition with the given - Id. - - :param mongo_role_definition_id: The ID for the Role Definition {dbName.roleName}. Required. - :type mongo_role_definition_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: MongoRoleDefinitionGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.MongoRoleDefinitionGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MongoRoleDefinitionGetResults] = kwargs.pop("cls", None) - - _request = build_get_mongo_role_definition_request( - mongo_role_definition_id=mongo_role_definition_id, - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("MongoRoleDefinitionGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _create_update_mongo_role_definition_initial( # pylint: disable=name-too-long - self, - mongo_role_definition_id: str, - resource_group_name: str, - account_name: str, - create_update_mongo_role_definition_parameters: Union[ - _models.MongoRoleDefinitionCreateUpdateParameters, IO[bytes] - ], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_mongo_role_definition_parameters, (IOBase, bytes)): - _content = create_update_mongo_role_definition_parameters - else: - _json = self._serialize.body( - create_update_mongo_role_definition_parameters, "MongoRoleDefinitionCreateUpdateParameters" - ) - - _request = build_create_update_mongo_role_definition_request( - mongo_role_definition_id=mongo_role_definition_id, - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_update_mongo_role_definition( # pylint: disable=name-too-long - self, - mongo_role_definition_id: str, - resource_group_name: str, - account_name: str, - create_update_mongo_role_definition_parameters: _models.MongoRoleDefinitionCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.MongoRoleDefinitionGetResults]: - """Creates or updates an Azure Cosmos DB Mongo Role Definition. - - :param mongo_role_definition_id: The ID for the Role Definition {dbName.roleName}. Required. - :type mongo_role_definition_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param create_update_mongo_role_definition_parameters: The properties required to create or - update a Role Definition. Required. - :type create_update_mongo_role_definition_parameters: - ~azure.mgmt.cosmosdb.models.MongoRoleDefinitionCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either MongoRoleDefinitionGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoRoleDefinitionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_update_mongo_role_definition( # pylint: disable=name-too-long - self, - mongo_role_definition_id: str, - resource_group_name: str, - account_name: str, - create_update_mongo_role_definition_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.MongoRoleDefinitionGetResults]: - """Creates or updates an Azure Cosmos DB Mongo Role Definition. - - :param mongo_role_definition_id: The ID for the Role Definition {dbName.roleName}. Required. - :type mongo_role_definition_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param create_update_mongo_role_definition_parameters: The properties required to create or - update a Role Definition. Required. - :type create_update_mongo_role_definition_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either MongoRoleDefinitionGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoRoleDefinitionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_update_mongo_role_definition( # pylint: disable=name-too-long - self, - mongo_role_definition_id: str, - resource_group_name: str, - account_name: str, - create_update_mongo_role_definition_parameters: Union[ - _models.MongoRoleDefinitionCreateUpdateParameters, IO[bytes] - ], - **kwargs: Any - ) -> AsyncLROPoller[_models.MongoRoleDefinitionGetResults]: - """Creates or updates an Azure Cosmos DB Mongo Role Definition. - - :param mongo_role_definition_id: The ID for the Role Definition {dbName.roleName}. Required. - :type mongo_role_definition_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param create_update_mongo_role_definition_parameters: The properties required to create or - update a Role Definition. Is either a MongoRoleDefinitionCreateUpdateParameters type or a - IO[bytes] type. Required. - :type create_update_mongo_role_definition_parameters: - ~azure.mgmt.cosmosdb.models.MongoRoleDefinitionCreateUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either MongoRoleDefinitionGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoRoleDefinitionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.MongoRoleDefinitionGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_update_mongo_role_definition_initial( - mongo_role_definition_id=mongo_role_definition_id, - resource_group_name=resource_group_name, - account_name=account_name, - create_update_mongo_role_definition_parameters=create_update_mongo_role_definition_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("MongoRoleDefinitionGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.MongoRoleDefinitionGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.MongoRoleDefinitionGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _delete_mongo_role_definition_initial( - self, mongo_role_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_mongo_role_definition_request( - mongo_role_definition_id=mongo_role_definition_id, - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202, 204]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete_mongo_role_definition( - self, mongo_role_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes an existing Azure Cosmos DB Mongo Role Definition. - - :param mongo_role_definition_id: The ID for the Role Definition {dbName.roleName}. Required. - :type mongo_role_definition_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_mongo_role_definition_initial( - mongo_role_definition_id=mongo_role_definition_id, - resource_group_name=resource_group_name, - account_name=account_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace - def list_mongo_role_definitions( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> AsyncIterable["_models.MongoRoleDefinitionGetResults"]: - """Retrieves the list of all Azure Cosmos DB Mongo Role Definitions. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either MongoRoleDefinitionGetResults or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.MongoRoleDefinitionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MongoRoleDefinitionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_mongo_role_definitions_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("MongoRoleDefinitionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get_mongo_user_definition( - self, mongo_user_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any - ) -> _models.MongoUserDefinitionGetResults: - """Retrieves the properties of an existing Azure Cosmos DB Mongo User Definition with the given - Id. - - :param mongo_user_definition_id: The ID for the User Definition {dbName.userName}. Required. - :type mongo_user_definition_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: MongoUserDefinitionGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.MongoUserDefinitionGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MongoUserDefinitionGetResults] = kwargs.pop("cls", None) - - _request = build_get_mongo_user_definition_request( - mongo_user_definition_id=mongo_user_definition_id, - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("MongoUserDefinitionGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _create_update_mongo_user_definition_initial( # pylint: disable=name-too-long - self, - mongo_user_definition_id: str, - resource_group_name: str, - account_name: str, - create_update_mongo_user_definition_parameters: Union[ - _models.MongoUserDefinitionCreateUpdateParameters, IO[bytes] - ], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_mongo_user_definition_parameters, (IOBase, bytes)): - _content = create_update_mongo_user_definition_parameters - else: - _json = self._serialize.body( - create_update_mongo_user_definition_parameters, "MongoUserDefinitionCreateUpdateParameters" - ) - - _request = build_create_update_mongo_user_definition_request( - mongo_user_definition_id=mongo_user_definition_id, - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_update_mongo_user_definition( # pylint: disable=name-too-long - self, - mongo_user_definition_id: str, - resource_group_name: str, - account_name: str, - create_update_mongo_user_definition_parameters: _models.MongoUserDefinitionCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.MongoUserDefinitionGetResults]: - """Creates or updates an Azure Cosmos DB Mongo User Definition. - - :param mongo_user_definition_id: The ID for the User Definition {dbName.userName}. Required. - :type mongo_user_definition_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param create_update_mongo_user_definition_parameters: The properties required to create or - update a User Definition. Required. - :type create_update_mongo_user_definition_parameters: - ~azure.mgmt.cosmosdb.models.MongoUserDefinitionCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either MongoUserDefinitionGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoUserDefinitionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_update_mongo_user_definition( # pylint: disable=name-too-long - self, - mongo_user_definition_id: str, - resource_group_name: str, - account_name: str, - create_update_mongo_user_definition_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.MongoUserDefinitionGetResults]: - """Creates or updates an Azure Cosmos DB Mongo User Definition. - - :param mongo_user_definition_id: The ID for the User Definition {dbName.userName}. Required. - :type mongo_user_definition_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param create_update_mongo_user_definition_parameters: The properties required to create or - update a User Definition. Required. - :type create_update_mongo_user_definition_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either MongoUserDefinitionGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoUserDefinitionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_update_mongo_user_definition( # pylint: disable=name-too-long - self, - mongo_user_definition_id: str, - resource_group_name: str, - account_name: str, - create_update_mongo_user_definition_parameters: Union[ - _models.MongoUserDefinitionCreateUpdateParameters, IO[bytes] - ], - **kwargs: Any - ) -> AsyncLROPoller[_models.MongoUserDefinitionGetResults]: - """Creates or updates an Azure Cosmos DB Mongo User Definition. - - :param mongo_user_definition_id: The ID for the User Definition {dbName.userName}. Required. - :type mongo_user_definition_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param create_update_mongo_user_definition_parameters: The properties required to create or - update a User Definition. Is either a MongoUserDefinitionCreateUpdateParameters type or a - IO[bytes] type. Required. - :type create_update_mongo_user_definition_parameters: - ~azure.mgmt.cosmosdb.models.MongoUserDefinitionCreateUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either MongoUserDefinitionGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoUserDefinitionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.MongoUserDefinitionGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_update_mongo_user_definition_initial( - mongo_user_definition_id=mongo_user_definition_id, - resource_group_name=resource_group_name, - account_name=account_name, - create_update_mongo_user_definition_parameters=create_update_mongo_user_definition_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("MongoUserDefinitionGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.MongoUserDefinitionGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.MongoUserDefinitionGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _delete_mongo_user_definition_initial( - self, mongo_user_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_mongo_user_definition_request( - mongo_user_definition_id=mongo_user_definition_id, - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202, 204]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete_mongo_user_definition( - self, mongo_user_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes an existing Azure Cosmos DB Mongo User Definition. - - :param mongo_user_definition_id: The ID for the User Definition {dbName.userName}. Required. - :type mongo_user_definition_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_mongo_user_definition_initial( - mongo_user_definition_id=mongo_user_definition_id, - resource_group_name=resource_group_name, - account_name=account_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace - def list_mongo_user_definitions( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> AsyncIterable["_models.MongoUserDefinitionGetResults"]: - """Retrieves the list of all Azure Cosmos DB Mongo User Definition. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either MongoUserDefinitionGetResults or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.MongoUserDefinitionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MongoUserDefinitionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_mongo_user_definitions_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("MongoUserDefinitionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - async def _retrieve_continuous_backup_information_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(location, (IOBase, bytes)): - _content = location - else: - _json = self._serialize.body(location, "ContinuousBackupRestoreLocation") - - _request = build_retrieve_continuous_backup_information_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - location: _models.ContinuousBackupRestoreLocation, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.BackupInformation]: - """Retrieves continuous backup information for a Mongodb collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param location: The name of the continuous backup restore location. Required. - :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either BackupInformation or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - location: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.BackupInformation]: - """Retrieves continuous backup information for a Mongodb collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param location: The name of the continuous backup restore location. Required. - :type location: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either BackupInformation or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.BackupInformation]: - """Retrieves continuous backup information for a Mongodb collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param location: The name of the continuous backup restore location. Is either a - ContinuousBackupRestoreLocation type or a IO[bytes] type. Required. - :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation or IO[bytes] - :return: An instance of AsyncLROPoller that returns either BackupInformation or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.BackupInformation] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._retrieve_continuous_backup_information_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - location=location, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("BackupInformation", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.BackupInformation].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.BackupInformation]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ...operations._mongo_db_resources_operations import ( + build_create_update_mongo_db_collection_request, + build_create_update_mongo_db_database_request, + build_create_update_mongo_role_definition_request, + build_create_update_mongo_user_definition_request, + build_delete_mongo_db_collection_request, + build_delete_mongo_db_database_request, + build_delete_mongo_role_definition_request, + build_delete_mongo_user_definition_request, + build_get_mongo_db_collection_request, + build_get_mongo_db_collection_throughput_request, + build_get_mongo_db_database_request, + build_get_mongo_db_database_throughput_request, + build_get_mongo_role_definition_request, + build_get_mongo_user_definition_request, + build_list_mongo_db_collection_partition_merge_request, + build_list_mongo_db_collections_request, + build_list_mongo_db_databases_request, + build_list_mongo_role_definitions_request, + build_list_mongo_user_definitions_request, + build_migrate_mongo_db_collection_to_autoscale_request, + build_migrate_mongo_db_collection_to_manual_throughput_request, + build_migrate_mongo_db_database_to_autoscale_request, + build_migrate_mongo_db_database_to_manual_throughput_request, + build_mongo_db_container_redistribute_throughput_request, + build_mongo_db_container_retrieve_throughput_distribution_request, + build_mongo_db_database_partition_merge_request, + build_mongo_db_database_redistribute_throughput_request, + build_mongo_db_database_retrieve_throughput_distribution_request, + build_retrieve_continuous_backup_information_request, + build_update_mongo_db_collection_throughput_request, + build_update_mongo_db_database_throughput_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class MongoDBResourcesOperations: # pylint: disable=too-many-public-methods + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`mongo_db_resources` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_mongo_db_databases( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> AsyncIterable["_models.MongoDBDatabaseGetResults"]: + """Lists the MongoDB databases under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either MongoDBDatabaseGetResults or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MongoDBDatabaseListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_mongo_db_databases_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("MongoDBDatabaseListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get_mongo_db_database( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> _models.MongoDBDatabaseGetResults: + """Gets the MongoDB databases under an existing Azure Cosmos DB database account with the provided + name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: MongoDBDatabaseGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MongoDBDatabaseGetResults] = kwargs.pop("cls", None) + + _request = build_get_mongo_db_database_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("MongoDBDatabaseGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_update_mongo_db_database_initial( + self, + resource_group_name: str, + account_name: str, + database_name: str, + create_update_mongo_db_database_parameters: Union[_models.MongoDBDatabaseCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_mongo_db_database_parameters, (IOBase, bytes)): + _content = create_update_mongo_db_database_parameters + else: + _json = self._serialize.body( + create_update_mongo_db_database_parameters, "MongoDBDatabaseCreateUpdateParameters" + ) + + _request = build_create_update_mongo_db_database_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_update_mongo_db_database( + self, + resource_group_name: str, + account_name: str, + database_name: str, + create_update_mongo_db_database_parameters: _models.MongoDBDatabaseCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.MongoDBDatabaseGetResults]: + """Create or updates Azure Cosmos DB MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param create_update_mongo_db_database_parameters: The parameters to provide for the current + MongoDB database. Required. + :type create_update_mongo_db_database_parameters: + ~azure.mgmt.cosmosdb.models.MongoDBDatabaseCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either MongoDBDatabaseGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_update_mongo_db_database( + self, + resource_group_name: str, + account_name: str, + database_name: str, + create_update_mongo_db_database_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.MongoDBDatabaseGetResults]: + """Create or updates Azure Cosmos DB MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param create_update_mongo_db_database_parameters: The parameters to provide for the current + MongoDB database. Required. + :type create_update_mongo_db_database_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either MongoDBDatabaseGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_update_mongo_db_database( + self, + resource_group_name: str, + account_name: str, + database_name: str, + create_update_mongo_db_database_parameters: Union[_models.MongoDBDatabaseCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.MongoDBDatabaseGetResults]: + """Create or updates Azure Cosmos DB MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param create_update_mongo_db_database_parameters: The parameters to provide for the current + MongoDB database. Is either a MongoDBDatabaseCreateUpdateParameters type or a IO[bytes] type. + Required. + :type create_update_mongo_db_database_parameters: + ~azure.mgmt.cosmosdb.models.MongoDBDatabaseCreateUpdateParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either MongoDBDatabaseGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.MongoDBDatabaseGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_update_mongo_db_database_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + create_update_mongo_db_database_parameters=create_update_mongo_db_database_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("MongoDBDatabaseGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.MongoDBDatabaseGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.MongoDBDatabaseGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_mongo_db_database_initial( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_mongo_db_database_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete_mongo_db_database( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes an existing Azure Cosmos DB MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_mongo_db_database_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace_async + async def get_mongo_db_database_throughput( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> _models.ThroughputSettingsGetResults: + """Gets the RUs per second of the MongoDB database under an existing Azure Cosmos DB database + account with the provided name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: ThroughputSettingsGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + + _request = build_get_mongo_db_database_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _update_mongo_db_database_throughput_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(update_throughput_parameters, (IOBase, bytes)): + _content = update_throughput_parameters + else: + _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") + + _request = build_update_mongo_db_database_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_update_mongo_db_database_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of the an Azure Cosmos DB MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current MongoDB database. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update_mongo_db_database_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + update_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of the an Azure Cosmos DB MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current MongoDB database. Required. + :type update_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update_mongo_db_database_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of the an Azure Cosmos DB MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current MongoDB database. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] + type. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._update_mongo_db_database_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + update_throughput_parameters=update_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _migrate_mongo_db_database_to_autoscale_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_mongo_db_database_to_autoscale_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_migrate_mongo_db_database_to_autoscale( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB MongoDB database from manual throughput to autoscale. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._migrate_mongo_db_database_to_autoscale_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _migrate_mongo_db_database_to_manual_throughput_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_mongo_db_database_to_manual_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_migrate_mongo_db_database_to_manual_throughput( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB MongoDB database from autoscale to manual throughput. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._migrate_mongo_db_database_to_manual_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _mongo_db_database_retrieve_throughput_distribution_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(retrieve_throughput_parameters, (IOBase, bytes)): + _content = retrieve_throughput_parameters + else: + _json = self._serialize.body(retrieve_throughput_parameters, "RetrieveThroughputParameters") + + _request = build_mongo_db_database_retrieve_throughput_distribution_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_mongo_db_database_retrieve_throughput_distribution( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + retrieve_throughput_parameters: _models.RetrieveThroughputParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Retrieve throughput distribution for an Azure Cosmos DB MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput + distribution for the current MongoDB database. Required. + :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionThroughputInfoResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_mongo_db_database_retrieve_throughput_distribution( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + retrieve_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Retrieve throughput distribution for an Azure Cosmos DB MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput + distribution for the current MongoDB database. Required. + :type retrieve_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionThroughputInfoResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_mongo_db_database_retrieve_throughput_distribution( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Retrieve throughput distribution for an Azure Cosmos DB MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput + distribution for the current MongoDB database. Is either a RetrieveThroughputParameters type or + a IO[bytes] type. Required. + :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters + or IO[bytes] + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionThroughputInfoResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._mongo_db_database_retrieve_throughput_distribution_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + retrieve_throughput_parameters=retrieve_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _mongo_db_database_redistribute_throughput_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(redistribute_throughput_parameters, (IOBase, bytes)): + _content = redistribute_throughput_parameters + else: + _json = self._serialize.body(redistribute_throughput_parameters, "RedistributeThroughputParameters") + + _request = build_mongo_db_database_redistribute_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_mongo_db_database_redistribute_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + redistribute_throughput_parameters: _models.RedistributeThroughputParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Redistribute throughput for an Azure Cosmos DB MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param redistribute_throughput_parameters: The parameters to provide for redistributing + throughput for the current MongoDB database. Required. + :type redistribute_throughput_parameters: + ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionThroughputInfoResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_mongo_db_database_redistribute_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + redistribute_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Redistribute throughput for an Azure Cosmos DB MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param redistribute_throughput_parameters: The parameters to provide for redistributing + throughput for the current MongoDB database. Required. + :type redistribute_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionThroughputInfoResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_mongo_db_database_redistribute_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Redistribute throughput for an Azure Cosmos DB MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param redistribute_throughput_parameters: The parameters to provide for redistributing + throughput for the current MongoDB database. Is either a RedistributeThroughputParameters type + or a IO[bytes] type. Required. + :type redistribute_throughput_parameters: + ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionThroughputInfoResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._mongo_db_database_redistribute_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + redistribute_throughput_parameters=redistribute_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _mongo_db_container_retrieve_throughput_distribution_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(retrieve_throughput_parameters, (IOBase, bytes)): + _content = retrieve_throughput_parameters + else: + _json = self._serialize.body(retrieve_throughput_parameters, "RetrieveThroughputParameters") + + _request = build_mongo_db_container_retrieve_throughput_distribution_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_mongo_db_container_retrieve_throughput_distribution( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + retrieve_throughput_parameters: _models.RetrieveThroughputParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Retrieve throughput distribution for an Azure Cosmos DB MongoDB container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput + distribution for the current MongoDB container. Required. + :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionThroughputInfoResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_mongo_db_container_retrieve_throughput_distribution( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + retrieve_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Retrieve throughput distribution for an Azure Cosmos DB MongoDB container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput + distribution for the current MongoDB container. Required. + :type retrieve_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionThroughputInfoResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_mongo_db_container_retrieve_throughput_distribution( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Retrieve throughput distribution for an Azure Cosmos DB MongoDB container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput + distribution for the current MongoDB container. Is either a RetrieveThroughputParameters type + or a IO[bytes] type. Required. + :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters + or IO[bytes] + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionThroughputInfoResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._mongo_db_container_retrieve_throughput_distribution_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + retrieve_throughput_parameters=retrieve_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _mongo_db_container_redistribute_throughput_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(redistribute_throughput_parameters, (IOBase, bytes)): + _content = redistribute_throughput_parameters + else: + _json = self._serialize.body(redistribute_throughput_parameters, "RedistributeThroughputParameters") + + _request = build_mongo_db_container_redistribute_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_mongo_db_container_redistribute_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + redistribute_throughput_parameters: _models.RedistributeThroughputParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Redistribute throughput for an Azure Cosmos DB MongoDB container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param redistribute_throughput_parameters: The parameters to provide for redistributing + throughput for the current MongoDB container. Required. + :type redistribute_throughput_parameters: + ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionThroughputInfoResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_mongo_db_container_redistribute_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + redistribute_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Redistribute throughput for an Azure Cosmos DB MongoDB container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param redistribute_throughput_parameters: The parameters to provide for redistributing + throughput for the current MongoDB container. Required. + :type redistribute_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionThroughputInfoResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_mongo_db_container_redistribute_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Redistribute throughput for an Azure Cosmos DB MongoDB container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param redistribute_throughput_parameters: The parameters to provide for redistributing + throughput for the current MongoDB container. Is either a RedistributeThroughputParameters type + or a IO[bytes] type. Required. + :type redistribute_throughput_parameters: + ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionThroughputInfoResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._mongo_db_container_redistribute_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + redistribute_throughput_parameters=redistribute_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def list_mongo_db_collections( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> AsyncIterable["_models.MongoDBCollectionGetResults"]: + """Lists the MongoDB collection under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: An iterator like instance of either MongoDBCollectionGetResults or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.MongoDBCollectionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MongoDBCollectionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_mongo_db_collections_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("MongoDBCollectionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get_mongo_db_collection( + self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any + ) -> _models.MongoDBCollectionGetResults: + """Gets the MongoDB collection under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :return: MongoDBCollectionGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.MongoDBCollectionGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MongoDBCollectionGetResults] = kwargs.pop("cls", None) + + _request = build_get_mongo_db_collection_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("MongoDBCollectionGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_update_mongo_db_collection_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + create_update_mongo_db_collection_parameters: Union[_models.MongoDBCollectionCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_mongo_db_collection_parameters, (IOBase, bytes)): + _content = create_update_mongo_db_collection_parameters + else: + _json = self._serialize.body( + create_update_mongo_db_collection_parameters, "MongoDBCollectionCreateUpdateParameters" + ) + + _request = build_create_update_mongo_db_collection_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_update_mongo_db_collection( + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + create_update_mongo_db_collection_parameters: _models.MongoDBCollectionCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.MongoDBCollectionGetResults]: + """Create or update an Azure Cosmos DB MongoDB Collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param create_update_mongo_db_collection_parameters: The parameters to provide for the current + MongoDB Collection. Required. + :type create_update_mongo_db_collection_parameters: + ~azure.mgmt.cosmosdb.models.MongoDBCollectionCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either MongoDBCollectionGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoDBCollectionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_update_mongo_db_collection( + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + create_update_mongo_db_collection_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.MongoDBCollectionGetResults]: + """Create or update an Azure Cosmos DB MongoDB Collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param create_update_mongo_db_collection_parameters: The parameters to provide for the current + MongoDB Collection. Required. + :type create_update_mongo_db_collection_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either MongoDBCollectionGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoDBCollectionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_update_mongo_db_collection( + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + create_update_mongo_db_collection_parameters: Union[_models.MongoDBCollectionCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.MongoDBCollectionGetResults]: + """Create or update an Azure Cosmos DB MongoDB Collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param create_update_mongo_db_collection_parameters: The parameters to provide for the current + MongoDB Collection. Is either a MongoDBCollectionCreateUpdateParameters type or a IO[bytes] + type. Required. + :type create_update_mongo_db_collection_parameters: + ~azure.mgmt.cosmosdb.models.MongoDBCollectionCreateUpdateParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either MongoDBCollectionGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoDBCollectionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.MongoDBCollectionGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_update_mongo_db_collection_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + create_update_mongo_db_collection_parameters=create_update_mongo_db_collection_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("MongoDBCollectionGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.MongoDBCollectionGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.MongoDBCollectionGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_mongo_db_collection_initial( + self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_mongo_db_collection_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete_mongo_db_collection( + self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes an existing Azure Cosmos DB MongoDB Collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_mongo_db_collection_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + async def _mongo_db_database_partition_merge_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + merge_parameters: Union[_models.MergeParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(merge_parameters, (IOBase, bytes)): + _content = merge_parameters + else: + _json = self._serialize.body(merge_parameters, "MergeParameters") + + _request = build_mongo_db_database_partition_merge_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_mongo_db_database_partition_merge( + self, + resource_group_name: str, + account_name: str, + database_name: str, + merge_parameters: _models.MergeParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]: + """Merges the partitions of a MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param merge_parameters: The parameters for the merge operation. Required. + :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionStorageInfoCollection or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_mongo_db_database_partition_merge( + self, + resource_group_name: str, + account_name: str, + database_name: str, + merge_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]: + """Merges the partitions of a MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param merge_parameters: The parameters for the merge operation. Required. + :type merge_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionStorageInfoCollection or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_mongo_db_database_partition_merge( + self, + resource_group_name: str, + account_name: str, + database_name: str, + merge_parameters: Union[_models.MergeParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]: + """Merges the partitions of a MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param merge_parameters: The parameters for the merge operation. Is either a MergeParameters + type or a IO[bytes] type. Required. + :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionStorageInfoCollection or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PhysicalPartitionStorageInfoCollection] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._mongo_db_database_partition_merge_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + merge_parameters=merge_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("PhysicalPartitionStorageInfoCollection", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _list_mongo_db_collection_partition_merge_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + merge_parameters: Union[_models.MergeParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(merge_parameters, (IOBase, bytes)): + _content = merge_parameters + else: + _json = self._serialize.body(merge_parameters, "MergeParameters") + + _request = build_list_mongo_db_collection_partition_merge_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_list_mongo_db_collection_partition_merge( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + merge_parameters: _models.MergeParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]: + """Merges the partitions of a MongoDB Collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param merge_parameters: The parameters for the merge operation. Required. + :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionStorageInfoCollection or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_list_mongo_db_collection_partition_merge( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + merge_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]: + """Merges the partitions of a MongoDB Collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param merge_parameters: The parameters for the merge operation. Required. + :type merge_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionStorageInfoCollection or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_list_mongo_db_collection_partition_merge( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + merge_parameters: Union[_models.MergeParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]: + """Merges the partitions of a MongoDB Collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param merge_parameters: The parameters for the merge operation. Is either a MergeParameters + type or a IO[bytes] type. Required. + :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionStorageInfoCollection or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PhysicalPartitionStorageInfoCollection] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._list_mongo_db_collection_partition_merge_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + merge_parameters=merge_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("PhysicalPartitionStorageInfoCollection", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace_async + async def get_mongo_db_collection_throughput( + self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any + ) -> _models.ThroughputSettingsGetResults: + """Gets the RUs per second of the MongoDB collection under an existing Azure Cosmos DB database + account with the provided name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :return: ThroughputSettingsGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + + _request = build_get_mongo_db_collection_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _update_mongo_db_collection_throughput_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(update_throughput_parameters, (IOBase, bytes)): + _content = update_throughput_parameters + else: + _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") + + _request = build_update_mongo_db_collection_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_update_mongo_db_collection_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Update the RUs per second of an Azure Cosmos DB MongoDB collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current MongoDB collection. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update_mongo_db_collection_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + update_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Update the RUs per second of an Azure Cosmos DB MongoDB collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current MongoDB collection. Required. + :type update_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update_mongo_db_collection_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Update the RUs per second of an Azure Cosmos DB MongoDB collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current MongoDB collection. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] + type. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._update_mongo_db_collection_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + update_throughput_parameters=update_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _migrate_mongo_db_collection_to_autoscale_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_mongo_db_collection_to_autoscale_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_migrate_mongo_db_collection_to_autoscale( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB MongoDB collection from manual throughput to autoscale. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._migrate_mongo_db_collection_to_autoscale_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _migrate_mongo_db_collection_to_manual_throughput_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_mongo_db_collection_to_manual_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_migrate_mongo_db_collection_to_manual_throughput( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB MongoDB collection from autoscale to manual throughput. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._migrate_mongo_db_collection_to_manual_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace_async + async def get_mongo_role_definition( + self, mongo_role_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any + ) -> _models.MongoRoleDefinitionGetResults: + """Retrieves the properties of an existing Azure Cosmos DB Mongo Role Definition with the given + Id. + + :param mongo_role_definition_id: The ID for the Role Definition {dbName.roleName}. Required. + :type mongo_role_definition_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: MongoRoleDefinitionGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.MongoRoleDefinitionGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MongoRoleDefinitionGetResults] = kwargs.pop("cls", None) + + _request = build_get_mongo_role_definition_request( + mongo_role_definition_id=mongo_role_definition_id, + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("MongoRoleDefinitionGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_update_mongo_role_definition_initial( # pylint: disable=name-too-long + self, + mongo_role_definition_id: str, + resource_group_name: str, + account_name: str, + create_update_mongo_role_definition_parameters: Union[ + _models.MongoRoleDefinitionCreateUpdateParameters, IO[bytes] + ], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_mongo_role_definition_parameters, (IOBase, bytes)): + _content = create_update_mongo_role_definition_parameters + else: + _json = self._serialize.body( + create_update_mongo_role_definition_parameters, "MongoRoleDefinitionCreateUpdateParameters" + ) + + _request = build_create_update_mongo_role_definition_request( + mongo_role_definition_id=mongo_role_definition_id, + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_update_mongo_role_definition( # pylint: disable=name-too-long + self, + mongo_role_definition_id: str, + resource_group_name: str, + account_name: str, + create_update_mongo_role_definition_parameters: _models.MongoRoleDefinitionCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.MongoRoleDefinitionGetResults]: + """Creates or updates an Azure Cosmos DB Mongo Role Definition. + + :param mongo_role_definition_id: The ID for the Role Definition {dbName.roleName}. Required. + :type mongo_role_definition_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param create_update_mongo_role_definition_parameters: The properties required to create or + update a Role Definition. Required. + :type create_update_mongo_role_definition_parameters: + ~azure.mgmt.cosmosdb.models.MongoRoleDefinitionCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either MongoRoleDefinitionGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoRoleDefinitionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_update_mongo_role_definition( # pylint: disable=name-too-long + self, + mongo_role_definition_id: str, + resource_group_name: str, + account_name: str, + create_update_mongo_role_definition_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.MongoRoleDefinitionGetResults]: + """Creates or updates an Azure Cosmos DB Mongo Role Definition. + + :param mongo_role_definition_id: The ID for the Role Definition {dbName.roleName}. Required. + :type mongo_role_definition_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param create_update_mongo_role_definition_parameters: The properties required to create or + update a Role Definition. Required. + :type create_update_mongo_role_definition_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either MongoRoleDefinitionGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoRoleDefinitionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_update_mongo_role_definition( # pylint: disable=name-too-long + self, + mongo_role_definition_id: str, + resource_group_name: str, + account_name: str, + create_update_mongo_role_definition_parameters: Union[ + _models.MongoRoleDefinitionCreateUpdateParameters, IO[bytes] + ], + **kwargs: Any + ) -> AsyncLROPoller[_models.MongoRoleDefinitionGetResults]: + """Creates or updates an Azure Cosmos DB Mongo Role Definition. + + :param mongo_role_definition_id: The ID for the Role Definition {dbName.roleName}. Required. + :type mongo_role_definition_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param create_update_mongo_role_definition_parameters: The properties required to create or + update a Role Definition. Is either a MongoRoleDefinitionCreateUpdateParameters type or a + IO[bytes] type. Required. + :type create_update_mongo_role_definition_parameters: + ~azure.mgmt.cosmosdb.models.MongoRoleDefinitionCreateUpdateParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either MongoRoleDefinitionGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoRoleDefinitionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.MongoRoleDefinitionGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_update_mongo_role_definition_initial( + mongo_role_definition_id=mongo_role_definition_id, + resource_group_name=resource_group_name, + account_name=account_name, + create_update_mongo_role_definition_parameters=create_update_mongo_role_definition_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("MongoRoleDefinitionGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.MongoRoleDefinitionGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.MongoRoleDefinitionGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_mongo_role_definition_initial( + self, mongo_role_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_mongo_role_definition_request( + mongo_role_definition_id=mongo_role_definition_id, + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete_mongo_role_definition( + self, mongo_role_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes an existing Azure Cosmos DB Mongo Role Definition. + + :param mongo_role_definition_id: The ID for the Role Definition {dbName.roleName}. Required. + :type mongo_role_definition_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_mongo_role_definition_initial( + mongo_role_definition_id=mongo_role_definition_id, + resource_group_name=resource_group_name, + account_name=account_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def list_mongo_role_definitions( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> AsyncIterable["_models.MongoRoleDefinitionGetResults"]: + """Retrieves the list of all Azure Cosmos DB Mongo Role Definitions. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either MongoRoleDefinitionGetResults or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.MongoRoleDefinitionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MongoRoleDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_mongo_role_definitions_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("MongoRoleDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get_mongo_user_definition( + self, mongo_user_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any + ) -> _models.MongoUserDefinitionGetResults: + """Retrieves the properties of an existing Azure Cosmos DB Mongo User Definition with the given + Id. + + :param mongo_user_definition_id: The ID for the User Definition {dbName.userName}. Required. + :type mongo_user_definition_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: MongoUserDefinitionGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.MongoUserDefinitionGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MongoUserDefinitionGetResults] = kwargs.pop("cls", None) + + _request = build_get_mongo_user_definition_request( + mongo_user_definition_id=mongo_user_definition_id, + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("MongoUserDefinitionGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_update_mongo_user_definition_initial( # pylint: disable=name-too-long + self, + mongo_user_definition_id: str, + resource_group_name: str, + account_name: str, + create_update_mongo_user_definition_parameters: Union[ + _models.MongoUserDefinitionCreateUpdateParameters, IO[bytes] + ], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_mongo_user_definition_parameters, (IOBase, bytes)): + _content = create_update_mongo_user_definition_parameters + else: + _json = self._serialize.body( + create_update_mongo_user_definition_parameters, "MongoUserDefinitionCreateUpdateParameters" + ) + + _request = build_create_update_mongo_user_definition_request( + mongo_user_definition_id=mongo_user_definition_id, + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_update_mongo_user_definition( # pylint: disable=name-too-long + self, + mongo_user_definition_id: str, + resource_group_name: str, + account_name: str, + create_update_mongo_user_definition_parameters: _models.MongoUserDefinitionCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.MongoUserDefinitionGetResults]: + """Creates or updates an Azure Cosmos DB Mongo User Definition. + + :param mongo_user_definition_id: The ID for the User Definition {dbName.userName}. Required. + :type mongo_user_definition_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param create_update_mongo_user_definition_parameters: The properties required to create or + update a User Definition. Required. + :type create_update_mongo_user_definition_parameters: + ~azure.mgmt.cosmosdb.models.MongoUserDefinitionCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either MongoUserDefinitionGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoUserDefinitionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_update_mongo_user_definition( # pylint: disable=name-too-long + self, + mongo_user_definition_id: str, + resource_group_name: str, + account_name: str, + create_update_mongo_user_definition_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.MongoUserDefinitionGetResults]: + """Creates or updates an Azure Cosmos DB Mongo User Definition. + + :param mongo_user_definition_id: The ID for the User Definition {dbName.userName}. Required. + :type mongo_user_definition_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param create_update_mongo_user_definition_parameters: The properties required to create or + update a User Definition. Required. + :type create_update_mongo_user_definition_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either MongoUserDefinitionGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoUserDefinitionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_update_mongo_user_definition( # pylint: disable=name-too-long + self, + mongo_user_definition_id: str, + resource_group_name: str, + account_name: str, + create_update_mongo_user_definition_parameters: Union[ + _models.MongoUserDefinitionCreateUpdateParameters, IO[bytes] + ], + **kwargs: Any + ) -> AsyncLROPoller[_models.MongoUserDefinitionGetResults]: + """Creates or updates an Azure Cosmos DB Mongo User Definition. + + :param mongo_user_definition_id: The ID for the User Definition {dbName.userName}. Required. + :type mongo_user_definition_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param create_update_mongo_user_definition_parameters: The properties required to create or + update a User Definition. Is either a MongoUserDefinitionCreateUpdateParameters type or a + IO[bytes] type. Required. + :type create_update_mongo_user_definition_parameters: + ~azure.mgmt.cosmosdb.models.MongoUserDefinitionCreateUpdateParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either MongoUserDefinitionGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoUserDefinitionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.MongoUserDefinitionGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_update_mongo_user_definition_initial( + mongo_user_definition_id=mongo_user_definition_id, + resource_group_name=resource_group_name, + account_name=account_name, + create_update_mongo_user_definition_parameters=create_update_mongo_user_definition_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("MongoUserDefinitionGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.MongoUserDefinitionGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.MongoUserDefinitionGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_mongo_user_definition_initial( + self, mongo_user_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_mongo_user_definition_request( + mongo_user_definition_id=mongo_user_definition_id, + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete_mongo_user_definition( + self, mongo_user_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes an existing Azure Cosmos DB Mongo User Definition. + + :param mongo_user_definition_id: The ID for the User Definition {dbName.userName}. Required. + :type mongo_user_definition_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_mongo_user_definition_initial( + mongo_user_definition_id=mongo_user_definition_id, + resource_group_name=resource_group_name, + account_name=account_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def list_mongo_user_definitions( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> AsyncIterable["_models.MongoUserDefinitionGetResults"]: + """Retrieves the list of all Azure Cosmos DB Mongo User Definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either MongoUserDefinitionGetResults or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.MongoUserDefinitionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MongoUserDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_mongo_user_definitions_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("MongoUserDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + async def _retrieve_continuous_backup_information_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(location, (IOBase, bytes)): + _content = location + else: + _json = self._serialize.body(location, "ContinuousBackupRestoreLocation") + + _request = build_retrieve_continuous_backup_information_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + location: _models.ContinuousBackupRestoreLocation, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.BackupInformation]: + """Retrieves continuous backup information for a Mongodb collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param location: The name of the continuous backup restore location. Required. + :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either BackupInformation or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + location: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.BackupInformation]: + """Retrieves continuous backup information for a Mongodb collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param location: The name of the continuous backup restore location. Required. + :type location: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either BackupInformation or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.BackupInformation]: + """Retrieves continuous backup information for a Mongodb collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param location: The name of the continuous backup restore location. Is either a + ContinuousBackupRestoreLocation type or a IO[bytes] type. Required. + :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation or IO[bytes] + :return: An instance of AsyncLROPoller that returns either BackupInformation or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.BackupInformation] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._retrieve_continuous_backup_information_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + location=location, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("BackupInformation", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.BackupInformation].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.BackupInformation]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_network_security_perimeter_configurations_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_network_security_perimeter_configurations_operations.py index d9f94f296fd..aa3e304fa47 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_network_security_perimeter_configurations_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_network_security_perimeter_configurations_operations.py @@ -1,341 +1,341 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, Optional, Type, TypeVar, Union, cast -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling - -from ... import models as _models -from ...operations._network_security_perimeter_configurations_operations import ( - build_get_request, - build_list_request, - build_reconcile_request, -) - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class NetworkSecurityPerimeterConfigurationsOperations: # pylint: disable=name-too-long - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`network_security_perimeter_configurations` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> AsyncIterable["_models.NetworkSecurityPerimeterConfiguration"]: - """Gets list of effective Network Security Perimeter Configuration for cosmos db account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either NetworkSecurityPerimeterConfiguration or the - result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.NetworkSecurityPerimeterConfiguration] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.NetworkSecurityPerimeterConfigurationListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("NetworkSecurityPerimeterConfigurationListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get( - self, - resource_group_name: str, - account_name: str, - network_security_perimeter_configuration_name: str, - **kwargs: Any - ) -> _models.NetworkSecurityPerimeterConfiguration: - """Gets effective Network Security Perimeter Configuration for association. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param network_security_perimeter_configuration_name: The name for Network Security Perimeter - configuration. Required. - :type network_security_perimeter_configuration_name: str - :return: NetworkSecurityPerimeterConfiguration or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.NetworkSecurityPerimeterConfiguration - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.NetworkSecurityPerimeterConfiguration] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - account_name=account_name, - network_security_perimeter_configuration_name=network_security_perimeter_configuration_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("NetworkSecurityPerimeterConfiguration", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _reconcile_initial( - self, - resource_group_name: str, - account_name: str, - network_security_perimeter_configuration_name: str, - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_reconcile_request( - resource_group_name=resource_group_name, - account_name=account_name, - network_security_perimeter_configuration_name=network_security_perimeter_configuration_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_reconcile( - self, - resource_group_name: str, - account_name: str, - network_security_perimeter_configuration_name: str, - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Refreshes any information about the association. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param network_security_perimeter_configuration_name: The name for Network Security Perimeter - configuration. Required. - :type network_security_perimeter_configuration_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._reconcile_initial( - resource_group_name=resource_group_name, - account_name=account_name, - network_security_perimeter_configuration_name=network_security_perimeter_configuration_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, Optional, Type, TypeVar, Union, cast +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ...operations._network_security_perimeter_configurations_operations import ( + build_get_request, + build_list_request, + build_reconcile_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class NetworkSecurityPerimeterConfigurationsOperations: # pylint: disable=name-too-long + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`network_security_perimeter_configurations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> AsyncIterable["_models.NetworkSecurityPerimeterConfiguration"]: + """Gets list of effective Network Security Perimeter Configuration for cosmos db account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either NetworkSecurityPerimeterConfiguration or the + result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.NetworkSecurityPerimeterConfiguration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.NetworkSecurityPerimeterConfigurationListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("NetworkSecurityPerimeterConfigurationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get( + self, + resource_group_name: str, + account_name: str, + network_security_perimeter_configuration_name: str, + **kwargs: Any + ) -> _models.NetworkSecurityPerimeterConfiguration: + """Gets effective Network Security Perimeter Configuration for association. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param network_security_perimeter_configuration_name: The name for Network Security Perimeter + configuration. Required. + :type network_security_perimeter_configuration_name: str + :return: NetworkSecurityPerimeterConfiguration or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.NetworkSecurityPerimeterConfiguration + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.NetworkSecurityPerimeterConfiguration] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + account_name=account_name, + network_security_perimeter_configuration_name=network_security_perimeter_configuration_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("NetworkSecurityPerimeterConfiguration", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _reconcile_initial( + self, + resource_group_name: str, + account_name: str, + network_security_perimeter_configuration_name: str, + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_reconcile_request( + resource_group_name=resource_group_name, + account_name=account_name, + network_security_perimeter_configuration_name=network_security_perimeter_configuration_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_reconcile( + self, + resource_group_name: str, + account_name: str, + network_security_perimeter_configuration_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Refreshes any information about the association. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param network_security_perimeter_configuration_name: The name for Network Security Perimeter + configuration. Required. + :type network_security_perimeter_configuration_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._reconcile_initial( + resource_group_name=resource_group_name, + account_name=account_name, + network_security_perimeter_configuration_name=network_security_perimeter_configuration_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_notebook_workspaces_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_notebook_workspaces_operations.py index 4a863f9fe1b..bbd7e6ab073 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_notebook_workspaces_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_notebook_workspaces_operations.py @@ -1,856 +1,856 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling - -from ... import models as _models -from ...operations._notebook_workspaces_operations import ( - build_create_or_update_request, - build_delete_request, - build_get_request, - build_list_by_database_account_request, - build_list_connection_info_request, - build_regenerate_auth_token_request, - build_start_request, -) - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class NotebookWorkspacesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`notebook_workspaces` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_by_database_account( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> AsyncIterable["_models.NotebookWorkspace"]: - """Gets the notebook workspace resources of an existing Cosmos DB account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either NotebookWorkspace or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.NotebookWorkspace] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.NotebookWorkspaceListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_by_database_account_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("NotebookWorkspaceListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get( - self, - resource_group_name: str, - account_name: str, - notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], - **kwargs: Any - ) -> _models.NotebookWorkspace: - """Gets the notebook workspace for a Cosmos DB account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param notebook_workspace_name: The name of the notebook workspace resource. "default" - Required. - :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName - :return: NotebookWorkspace or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.NotebookWorkspace - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.NotebookWorkspace] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - account_name=account_name, - notebook_workspace_name=notebook_workspace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("NotebookWorkspace", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _create_or_update_initial( - self, - resource_group_name: str, - account_name: str, - notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], - notebook_create_update_parameters: Union[_models.NotebookWorkspaceCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(notebook_create_update_parameters, (IOBase, bytes)): - _content = notebook_create_update_parameters - else: - _json = self._serialize.body(notebook_create_update_parameters, "NotebookWorkspaceCreateUpdateParameters") - - _request = build_create_or_update_request( - resource_group_name=resource_group_name, - account_name=account_name, - notebook_workspace_name=notebook_workspace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_or_update( - self, - resource_group_name: str, - account_name: str, - notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], - notebook_create_update_parameters: _models.NotebookWorkspaceCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.NotebookWorkspace]: - """Creates the notebook workspace for a Cosmos DB account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param notebook_workspace_name: The name of the notebook workspace resource. "default" - Required. - :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName - :param notebook_create_update_parameters: The notebook workspace to create for the current - database account. Required. - :type notebook_create_update_parameters: - ~azure.mgmt.cosmosdb.models.NotebookWorkspaceCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either NotebookWorkspace or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.NotebookWorkspace] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_or_update( - self, - resource_group_name: str, - account_name: str, - notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], - notebook_create_update_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.NotebookWorkspace]: - """Creates the notebook workspace for a Cosmos DB account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param notebook_workspace_name: The name of the notebook workspace resource. "default" - Required. - :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName - :param notebook_create_update_parameters: The notebook workspace to create for the current - database account. Required. - :type notebook_create_update_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either NotebookWorkspace or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.NotebookWorkspace] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_or_update( - self, - resource_group_name: str, - account_name: str, - notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], - notebook_create_update_parameters: Union[_models.NotebookWorkspaceCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.NotebookWorkspace]: - """Creates the notebook workspace for a Cosmos DB account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param notebook_workspace_name: The name of the notebook workspace resource. "default" - Required. - :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName - :param notebook_create_update_parameters: The notebook workspace to create for the current - database account. Is either a NotebookWorkspaceCreateUpdateParameters type or a IO[bytes] type. - Required. - :type notebook_create_update_parameters: - ~azure.mgmt.cosmosdb.models.NotebookWorkspaceCreateUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either NotebookWorkspace or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.NotebookWorkspace] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.NotebookWorkspace] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_or_update_initial( - resource_group_name=resource_group_name, - account_name=account_name, - notebook_workspace_name=notebook_workspace_name, - notebook_create_update_parameters=notebook_create_update_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("NotebookWorkspace", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.NotebookWorkspace].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.NotebookWorkspace]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _delete_initial( - self, - resource_group_name: str, - account_name: str, - notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - account_name=account_name, - notebook_workspace_name=notebook_workspace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete( - self, - resource_group_name: str, - account_name: str, - notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes the notebook workspace for a Cosmos DB account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param notebook_workspace_name: The name of the notebook workspace resource. "default" - Required. - :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_initial( - resource_group_name=resource_group_name, - account_name=account_name, - notebook_workspace_name=notebook_workspace_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace_async - async def list_connection_info( - self, - resource_group_name: str, - account_name: str, - notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], - **kwargs: Any - ) -> _models.NotebookWorkspaceConnectionInfoResult: - """Retrieves the connection info for the notebook workspace. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param notebook_workspace_name: The name of the notebook workspace resource. "default" - Required. - :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName - :return: NotebookWorkspaceConnectionInfoResult or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.NotebookWorkspaceConnectionInfoResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.NotebookWorkspaceConnectionInfoResult] = kwargs.pop("cls", None) - - _request = build_list_connection_info_request( - resource_group_name=resource_group_name, - account_name=account_name, - notebook_workspace_name=notebook_workspace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("NotebookWorkspaceConnectionInfoResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _regenerate_auth_token_initial( - self, - resource_group_name: str, - account_name: str, - notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_regenerate_auth_token_request( - resource_group_name=resource_group_name, - account_name=account_name, - notebook_workspace_name=notebook_workspace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_regenerate_auth_token( - self, - resource_group_name: str, - account_name: str, - notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Regenerates the auth token for the notebook workspace. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param notebook_workspace_name: The name of the notebook workspace resource. "default" - Required. - :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._regenerate_auth_token_initial( - resource_group_name=resource_group_name, - account_name=account_name, - notebook_workspace_name=notebook_workspace_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - async def _start_initial( - self, - resource_group_name: str, - account_name: str, - notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_start_request( - resource_group_name=resource_group_name, - account_name=account_name, - notebook_workspace_name=notebook_workspace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_start( - self, - resource_group_name: str, - account_name: str, - notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Starts the notebook workspace. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param notebook_workspace_name: The name of the notebook workspace resource. "default" - Required. - :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._start_initial( - resource_group_name=resource_group_name, - account_name=account_name, - notebook_workspace_name=notebook_workspace_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ...operations._notebook_workspaces_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_database_account_request, + build_list_connection_info_request, + build_regenerate_auth_token_request, + build_start_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class NotebookWorkspacesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`notebook_workspaces` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_by_database_account( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> AsyncIterable["_models.NotebookWorkspace"]: + """Gets the notebook workspace resources of an existing Cosmos DB account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either NotebookWorkspace or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.NotebookWorkspace] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.NotebookWorkspaceListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_database_account_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("NotebookWorkspaceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get( + self, + resource_group_name: str, + account_name: str, + notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], + **kwargs: Any + ) -> _models.NotebookWorkspace: + """Gets the notebook workspace for a Cosmos DB account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param notebook_workspace_name: The name of the notebook workspace resource. "default" + Required. + :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName + :return: NotebookWorkspace or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.NotebookWorkspace + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.NotebookWorkspace] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + account_name=account_name, + notebook_workspace_name=notebook_workspace_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("NotebookWorkspace", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_or_update_initial( + self, + resource_group_name: str, + account_name: str, + notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], + notebook_create_update_parameters: Union[_models.NotebookWorkspaceCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(notebook_create_update_parameters, (IOBase, bytes)): + _content = notebook_create_update_parameters + else: + _json = self._serialize.body(notebook_create_update_parameters, "NotebookWorkspaceCreateUpdateParameters") + + _request = build_create_or_update_request( + resource_group_name=resource_group_name, + account_name=account_name, + notebook_workspace_name=notebook_workspace_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + account_name: str, + notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], + notebook_create_update_parameters: _models.NotebookWorkspaceCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.NotebookWorkspace]: + """Creates the notebook workspace for a Cosmos DB account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param notebook_workspace_name: The name of the notebook workspace resource. "default" + Required. + :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName + :param notebook_create_update_parameters: The notebook workspace to create for the current + database account. Required. + :type notebook_create_update_parameters: + ~azure.mgmt.cosmosdb.models.NotebookWorkspaceCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either NotebookWorkspace or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.NotebookWorkspace] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + account_name: str, + notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], + notebook_create_update_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.NotebookWorkspace]: + """Creates the notebook workspace for a Cosmos DB account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param notebook_workspace_name: The name of the notebook workspace resource. "default" + Required. + :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName + :param notebook_create_update_parameters: The notebook workspace to create for the current + database account. Required. + :type notebook_create_update_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either NotebookWorkspace or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.NotebookWorkspace] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + account_name: str, + notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], + notebook_create_update_parameters: Union[_models.NotebookWorkspaceCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.NotebookWorkspace]: + """Creates the notebook workspace for a Cosmos DB account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param notebook_workspace_name: The name of the notebook workspace resource. "default" + Required. + :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName + :param notebook_create_update_parameters: The notebook workspace to create for the current + database account. Is either a NotebookWorkspaceCreateUpdateParameters type or a IO[bytes] type. + Required. + :type notebook_create_update_parameters: + ~azure.mgmt.cosmosdb.models.NotebookWorkspaceCreateUpdateParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either NotebookWorkspace or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.NotebookWorkspace] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.NotebookWorkspace] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + account_name=account_name, + notebook_workspace_name=notebook_workspace_name, + notebook_create_update_parameters=notebook_create_update_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("NotebookWorkspace", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.NotebookWorkspace].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.NotebookWorkspace]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_initial( + self, + resource_group_name: str, + account_name: str, + notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + account_name=account_name, + notebook_workspace_name=notebook_workspace_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete( + self, + resource_group_name: str, + account_name: str, + notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes the notebook workspace for a Cosmos DB account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param notebook_workspace_name: The name of the notebook workspace resource. "default" + Required. + :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + account_name=account_name, + notebook_workspace_name=notebook_workspace_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace_async + async def list_connection_info( + self, + resource_group_name: str, + account_name: str, + notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], + **kwargs: Any + ) -> _models.NotebookWorkspaceConnectionInfoResult: + """Retrieves the connection info for the notebook workspace. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param notebook_workspace_name: The name of the notebook workspace resource. "default" + Required. + :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName + :return: NotebookWorkspaceConnectionInfoResult or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.NotebookWorkspaceConnectionInfoResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.NotebookWorkspaceConnectionInfoResult] = kwargs.pop("cls", None) + + _request = build_list_connection_info_request( + resource_group_name=resource_group_name, + account_name=account_name, + notebook_workspace_name=notebook_workspace_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("NotebookWorkspaceConnectionInfoResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _regenerate_auth_token_initial( + self, + resource_group_name: str, + account_name: str, + notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_regenerate_auth_token_request( + resource_group_name=resource_group_name, + account_name=account_name, + notebook_workspace_name=notebook_workspace_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_regenerate_auth_token( + self, + resource_group_name: str, + account_name: str, + notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Regenerates the auth token for the notebook workspace. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param notebook_workspace_name: The name of the notebook workspace resource. "default" + Required. + :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._regenerate_auth_token_initial( + resource_group_name=resource_group_name, + account_name=account_name, + notebook_workspace_name=notebook_workspace_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + async def _start_initial( + self, + resource_group_name: str, + account_name: str, + notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_start_request( + resource_group_name=resource_group_name, + account_name=account_name, + notebook_workspace_name=notebook_workspace_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_start( + self, + resource_group_name: str, + account_name: str, + notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Starts the notebook workspace. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param notebook_workspace_name: The name of the notebook workspace resource. "default" + Required. + :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._start_initial( + resource_group_name=resource_group_name, + account_name=account_name, + notebook_workspace_name=notebook_workspace_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_operations.py index 59558ac59df..374941add85 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_operations.py @@ -1,129 +1,129 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._operations import build_list_request - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class Operations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`operations` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: - """Lists all of the available Cosmos DB Resource Provider operations. - - :return: An iterator like instance of either Operation or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.Operation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("OperationListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._operations import build_list_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`operations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: + """Lists all of the available Cosmos DB Resource Provider operations. + + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_partition_key_range_id_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_partition_key_range_id_operations.py index ecf4e7969cc..e5719f865a4 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_partition_key_range_id_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_partition_key_range_id_operations.py @@ -1,160 +1,160 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._partition_key_range_id_operations import build_list_metrics_request - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class PartitionKeyRangeIdOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`partition_key_range_id` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_metrics( - self, - resource_group_name: str, - account_name: str, - database_rid: str, - collection_rid: str, - partition_key_range_id: str, - filter: str, - **kwargs: Any - ) -> AsyncIterable["_models.PartitionMetric"]: - """Retrieves the metrics determined by the given filter for the given partition key range id. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_rid: Cosmos DB database rid. Required. - :type database_rid: str - :param collection_rid: Cosmos DB collection rid. Required. - :type collection_rid: str - :param partition_key_range_id: Partition Key Range Id for which to get data. Required. - :type partition_key_range_id: str - :param filter: An OData filter expression that describes a subset of metrics to return. The - parameters that can be filtered are name.value (name of the metric, can have an or of multiple - names), startTime, endTime, and timeGrain. The supported operator is eq. Required. - :type filter: str - :return: An iterator like instance of either PartitionMetric or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.PartitionMetric] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.PartitionMetricListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_metrics_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_rid=database_rid, - collection_rid=collection_rid, - partition_key_range_id=partition_key_range_id, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PartitionMetricListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._partition_key_range_id_operations import build_list_metrics_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class PartitionKeyRangeIdOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`partition_key_range_id` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_metrics( + self, + resource_group_name: str, + account_name: str, + database_rid: str, + collection_rid: str, + partition_key_range_id: str, + filter: str, + **kwargs: Any + ) -> AsyncIterable["_models.PartitionMetric"]: + """Retrieves the metrics determined by the given filter for the given partition key range id. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_rid: Cosmos DB database rid. Required. + :type database_rid: str + :param collection_rid: Cosmos DB collection rid. Required. + :type collection_rid: str + :param partition_key_range_id: Partition Key Range Id for which to get data. Required. + :type partition_key_range_id: str + :param filter: An OData filter expression that describes a subset of metrics to return. The + parameters that can be filtered are name.value (name of the metric, can have an or of multiple + names), startTime, endTime, and timeGrain. The supported operator is eq. Required. + :type filter: str + :return: An iterator like instance of either PartitionMetric or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.PartitionMetric] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PartitionMetricListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_metrics_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_rid=database_rid, + collection_rid=collection_rid, + partition_key_range_id=partition_key_range_id, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PartitionMetricListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_partition_key_range_id_region_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_partition_key_range_id_region_operations.py index 242ea604414..81cab31b89d 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_partition_key_range_id_region_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_partition_key_range_id_region_operations.py @@ -1,165 +1,165 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._partition_key_range_id_region_operations import build_list_metrics_request - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class PartitionKeyRangeIdRegionOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`partition_key_range_id_region` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_metrics( - self, - resource_group_name: str, - account_name: str, - region: str, - database_rid: str, - collection_rid: str, - partition_key_range_id: str, - filter: str, - **kwargs: Any - ) -> AsyncIterable["_models.PartitionMetric"]: - """Retrieves the metrics determined by the given filter for the given partition key range id and - region. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param region: Cosmos DB region, with spaces between words and each word capitalized. Required. - :type region: str - :param database_rid: Cosmos DB database rid. Required. - :type database_rid: str - :param collection_rid: Cosmos DB collection rid. Required. - :type collection_rid: str - :param partition_key_range_id: Partition Key Range Id for which to get data. Required. - :type partition_key_range_id: str - :param filter: An OData filter expression that describes a subset of metrics to return. The - parameters that can be filtered are name.value (name of the metric, can have an or of multiple - names), startTime, endTime, and timeGrain. The supported operator is eq. Required. - :type filter: str - :return: An iterator like instance of either PartitionMetric or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.PartitionMetric] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.PartitionMetricListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_metrics_request( - resource_group_name=resource_group_name, - account_name=account_name, - region=region, - database_rid=database_rid, - collection_rid=collection_rid, - partition_key_range_id=partition_key_range_id, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PartitionMetricListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._partition_key_range_id_region_operations import build_list_metrics_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class PartitionKeyRangeIdRegionOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`partition_key_range_id_region` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_metrics( + self, + resource_group_name: str, + account_name: str, + region: str, + database_rid: str, + collection_rid: str, + partition_key_range_id: str, + filter: str, + **kwargs: Any + ) -> AsyncIterable["_models.PartitionMetric"]: + """Retrieves the metrics determined by the given filter for the given partition key range id and + region. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param region: Cosmos DB region, with spaces between words and each word capitalized. Required. + :type region: str + :param database_rid: Cosmos DB database rid. Required. + :type database_rid: str + :param collection_rid: Cosmos DB collection rid. Required. + :type collection_rid: str + :param partition_key_range_id: Partition Key Range Id for which to get data. Required. + :type partition_key_range_id: str + :param filter: An OData filter expression that describes a subset of metrics to return. The + parameters that can be filtered are name.value (name of the metric, can have an or of multiple + names), startTime, endTime, and timeGrain. The supported operator is eq. Required. + :type filter: str + :return: An iterator like instance of either PartitionMetric or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.PartitionMetric] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PartitionMetricListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_metrics_request( + resource_group_name=resource_group_name, + account_name=account_name, + region=region, + database_rid=database_rid, + collection_rid=collection_rid, + partition_key_range_id=partition_key_range_id, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PartitionMetricListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_patch.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_patch.py index 1bb0db275de..f7dd3251033 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_patch.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_patch.py @@ -1,20 +1,20 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_percentile_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_percentile_operations.py index 1e380112db4..9d20844c217 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_percentile_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_percentile_operations.py @@ -1,145 +1,145 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._percentile_operations import build_list_metrics_request - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class PercentileOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`percentile` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_metrics( - self, resource_group_name: str, account_name: str, filter: str, **kwargs: Any - ) -> AsyncIterable["_models.PercentileMetric"]: - """Retrieves the metrics determined by the given filter for the given database account. This url - is only for PBS and Replication Latency data. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param filter: An OData filter expression that describes a subset of metrics to return. The - parameters that can be filtered are name.value (name of the metric, can have an or of multiple - names), startTime, endTime, and timeGrain. The supported operator is eq. Required. - :type filter: str - :return: An iterator like instance of either PercentileMetric or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.PercentileMetric] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.PercentileMetricListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_metrics_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PercentileMetricListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._percentile_operations import build_list_metrics_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class PercentileOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`percentile` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_metrics( + self, resource_group_name: str, account_name: str, filter: str, **kwargs: Any + ) -> AsyncIterable["_models.PercentileMetric"]: + """Retrieves the metrics determined by the given filter for the given database account. This url + is only for PBS and Replication Latency data. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param filter: An OData filter expression that describes a subset of metrics to return. The + parameters that can be filtered are name.value (name of the metric, can have an or of multiple + names), startTime, endTime, and timeGrain. The supported operator is eq. Required. + :type filter: str + :return: An iterator like instance of either PercentileMetric or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.PercentileMetric] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PercentileMetricListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_metrics_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PercentileMetricListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_percentile_source_target_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_percentile_source_target_operations.py index 90d328b8e56..7703bb57011 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_percentile_source_target_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_percentile_source_target_operations.py @@ -1,159 +1,159 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._percentile_source_target_operations import build_list_metrics_request - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class PercentileSourceTargetOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`percentile_source_target` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_metrics( - self, - resource_group_name: str, - account_name: str, - source_region: str, - target_region: str, - filter: str, - **kwargs: Any - ) -> AsyncIterable["_models.PercentileMetric"]: - """Retrieves the metrics determined by the given filter for the given account, source and target - region. This url is only for PBS and Replication Latency data. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param source_region: Source region from which data is written. Cosmos DB region, with spaces - between words and each word capitalized. Required. - :type source_region: str - :param target_region: Target region to which data is written. Cosmos DB region, with spaces - between words and each word capitalized. Required. - :type target_region: str - :param filter: An OData filter expression that describes a subset of metrics to return. The - parameters that can be filtered are name.value (name of the metric, can have an or of multiple - names), startTime, endTime, and timeGrain. The supported operator is eq. Required. - :type filter: str - :return: An iterator like instance of either PercentileMetric or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.PercentileMetric] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.PercentileMetricListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_metrics_request( - resource_group_name=resource_group_name, - account_name=account_name, - source_region=source_region, - target_region=target_region, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PercentileMetricListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._percentile_source_target_operations import build_list_metrics_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class PercentileSourceTargetOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`percentile_source_target` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_metrics( + self, + resource_group_name: str, + account_name: str, + source_region: str, + target_region: str, + filter: str, + **kwargs: Any + ) -> AsyncIterable["_models.PercentileMetric"]: + """Retrieves the metrics determined by the given filter for the given account, source and target + region. This url is only for PBS and Replication Latency data. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param source_region: Source region from which data is written. Cosmos DB region, with spaces + between words and each word capitalized. Required. + :type source_region: str + :param target_region: Target region to which data is written. Cosmos DB region, with spaces + between words and each word capitalized. Required. + :type target_region: str + :param filter: An OData filter expression that describes a subset of metrics to return. The + parameters that can be filtered are name.value (name of the metric, can have an or of multiple + names), startTime, endTime, and timeGrain. The supported operator is eq. Required. + :type filter: str + :return: An iterator like instance of either PercentileMetric or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.PercentileMetric] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PercentileMetricListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_metrics_request( + resource_group_name=resource_group_name, + account_name=account_name, + source_region=source_region, + target_region=target_region, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PercentileMetricListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_percentile_target_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_percentile_target_operations.py index d3632a830f7..a3b1ae14db5 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_percentile_target_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_percentile_target_operations.py @@ -1,149 +1,149 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._percentile_target_operations import build_list_metrics_request - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class PercentileTargetOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`percentile_target` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_metrics( - self, resource_group_name: str, account_name: str, target_region: str, filter: str, **kwargs: Any - ) -> AsyncIterable["_models.PercentileMetric"]: - """Retrieves the metrics determined by the given filter for the given account target region. This - url is only for PBS and Replication Latency data. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param target_region: Target region to which data is written. Cosmos DB region, with spaces - between words and each word capitalized. Required. - :type target_region: str - :param filter: An OData filter expression that describes a subset of metrics to return. The - parameters that can be filtered are name.value (name of the metric, can have an or of multiple - names), startTime, endTime, and timeGrain. The supported operator is eq. Required. - :type filter: str - :return: An iterator like instance of either PercentileMetric or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.PercentileMetric] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.PercentileMetricListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_metrics_request( - resource_group_name=resource_group_name, - account_name=account_name, - target_region=target_region, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PercentileMetricListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._percentile_target_operations import build_list_metrics_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class PercentileTargetOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`percentile_target` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_metrics( + self, resource_group_name: str, account_name: str, target_region: str, filter: str, **kwargs: Any + ) -> AsyncIterable["_models.PercentileMetric"]: + """Retrieves the metrics determined by the given filter for the given account target region. This + url is only for PBS and Replication Latency data. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param target_region: Target region to which data is written. Cosmos DB region, with spaces + between words and each word capitalized. Required. + :type target_region: str + :param filter: An OData filter expression that describes a subset of metrics to return. The + parameters that can be filtered are name.value (name of the metric, can have an or of multiple + names), startTime, endTime, and timeGrain. The supported operator is eq. Required. + :type filter: str + :return: An iterator like instance of either PercentileMetric or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.PercentileMetric] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PercentileMetricListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_metrics_request( + resource_group_name=resource_group_name, + account_name=account_name, + target_region=target_region, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PercentileMetricListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_private_endpoint_connections_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_private_endpoint_connections_operations.py index ae9b07e66e9..972d2bd2c7d 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_private_endpoint_connections_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_private_endpoint_connections_operations.py @@ -1,529 +1,529 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling - -from ... import models as _models -from ...operations._private_endpoint_connections_operations import ( - build_create_or_update_request, - build_delete_request, - build_get_request, - build_list_by_database_account_request, -) - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class PrivateEndpointConnectionsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`private_endpoint_connections` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_by_database_account( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> AsyncIterable["_models.PrivateEndpointConnection"]: - """List all private endpoint connections on a Cosmos DB account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either PrivateEndpointConnection or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.PrivateEndpointConnection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.PrivateEndpointConnectionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_by_database_account_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PrivateEndpointConnectionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get( - self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, **kwargs: Any - ) -> _models.PrivateEndpointConnection: - """Gets a private endpoint connection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection. Required. - :type private_endpoint_connection_name: str - :return: PrivateEndpointConnection or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.PrivateEndpointConnection - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - account_name=account_name, - private_endpoint_connection_name=private_endpoint_connection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _create_or_update_initial( - self, - resource_group_name: str, - account_name: str, - private_endpoint_connection_name: str, - parameters: Union[_models.PrivateEndpointConnection, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PrivateEndpointConnection") - - _request = build_create_or_update_request( - resource_group_name=resource_group_name, - account_name=account_name, - private_endpoint_connection_name=private_endpoint_connection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_or_update( - self, - resource_group_name: str, - account_name: str, - private_endpoint_connection_name: str, - parameters: _models.PrivateEndpointConnection, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: - """Approve or reject a private endpoint connection with a given name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection. Required. - :type private_endpoint_connection_name: str - :param parameters: Required. - :type parameters: ~azure.mgmt.cosmosdb.models.PrivateEndpointConnection - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PrivateEndpointConnection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_or_update( - self, - resource_group_name: str, - account_name: str, - private_endpoint_connection_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: - """Approve or reject a private endpoint connection with a given name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection. Required. - :type private_endpoint_connection_name: str - :param parameters: Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PrivateEndpointConnection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_or_update( - self, - resource_group_name: str, - account_name: str, - private_endpoint_connection_name: str, - parameters: Union[_models.PrivateEndpointConnection, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: - """Approve or reject a private endpoint connection with a given name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection. Required. - :type private_endpoint_connection_name: str - :param parameters: Is either a PrivateEndpointConnection type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.cosmosdb.models.PrivateEndpointConnection or IO[bytes] - :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PrivateEndpointConnection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_or_update_initial( - resource_group_name=resource_group_name, - account_name=account_name, - private_endpoint_connection_name=private_endpoint_connection_name, - parameters=parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.PrivateEndpointConnection].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.PrivateEndpointConnection]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _delete_initial( - self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - account_name=account_name, - private_endpoint_connection_name=private_endpoint_connection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete( - self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes a private endpoint connection with a given name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection. Required. - :type private_endpoint_connection_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_initial( - resource_group_name=resource_group_name, - account_name=account_name, - private_endpoint_connection_name=private_endpoint_connection_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ...operations._private_endpoint_connections_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_database_account_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class PrivateEndpointConnectionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`private_endpoint_connections` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_by_database_account( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> AsyncIterable["_models.PrivateEndpointConnection"]: + """List all private endpoint connections on a Cosmos DB account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either PrivateEndpointConnection or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PrivateEndpointConnectionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_database_account_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PrivateEndpointConnectionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get( + self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, **kwargs: Any + ) -> _models.PrivateEndpointConnection: + """Gets a private endpoint connection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :return: PrivateEndpointConnection or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.PrivateEndpointConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + account_name=account_name, + private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_or_update_initial( + self, + resource_group_name: str, + account_name: str, + private_endpoint_connection_name: str, + parameters: Union[_models.PrivateEndpointConnection, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PrivateEndpointConnection") + + _request = build_create_or_update_request( + resource_group_name=resource_group_name, + account_name=account_name, + private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + account_name: str, + private_endpoint_connection_name: str, + parameters: _models.PrivateEndpointConnection, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: + """Approve or reject a private endpoint connection with a given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :param parameters: Required. + :type parameters: ~azure.mgmt.cosmosdb.models.PrivateEndpointConnection + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + account_name: str, + private_endpoint_connection_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: + """Approve or reject a private endpoint connection with a given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :param parameters: Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + account_name: str, + private_endpoint_connection_name: str, + parameters: Union[_models.PrivateEndpointConnection, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: + """Approve or reject a private endpoint connection with a given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :param parameters: Is either a PrivateEndpointConnection type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.cosmosdb.models.PrivateEndpointConnection or IO[bytes] + :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + account_name=account_name, + private_endpoint_connection_name=private_endpoint_connection_name, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.PrivateEndpointConnection].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.PrivateEndpointConnection]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_initial( + self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + account_name=account_name, + private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete( + self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes a private endpoint connection with a given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + account_name=account_name, + private_endpoint_connection_name=private_endpoint_connection_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_private_link_resources_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_private_link_resources_operations.py index 3dff6aeec15..e89692eb682 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_private_link_resources_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_private_link_resources_operations.py @@ -1,201 +1,201 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._private_link_resources_operations import build_get_request, build_list_by_database_account_request - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class PrivateLinkResourcesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`private_link_resources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_by_database_account( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> AsyncIterable["_models.PrivateLinkResource"]: - """Gets the private link resources that need to be created for a Cosmos DB account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either PrivateLinkResource or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.PrivateLinkResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.PrivateLinkResourceListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_by_database_account_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PrivateLinkResourceListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get( - self, resource_group_name: str, account_name: str, group_name: str, **kwargs: Any - ) -> _models.PrivateLinkResource: - """Gets the private link resources that need to be created for a Cosmos DB account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param group_name: The name of the private link resource. Required. - :type group_name: str - :return: PrivateLinkResource or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.PrivateLinkResource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.PrivateLinkResource] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - account_name=account_name, - group_name=group_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PrivateLinkResource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._private_link_resources_operations import build_get_request, build_list_by_database_account_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class PrivateLinkResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`private_link_resources` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_by_database_account( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> AsyncIterable["_models.PrivateLinkResource"]: + """Gets the private link resources that need to be created for a Cosmos DB account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either PrivateLinkResource or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.PrivateLinkResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PrivateLinkResourceListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_database_account_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PrivateLinkResourceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get( + self, resource_group_name: str, account_name: str, group_name: str, **kwargs: Any + ) -> _models.PrivateLinkResource: + """Gets the private link resources that need to be created for a Cosmos DB account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param group_name: The name of the private link resource. Required. + :type group_name: str + :return: PrivateLinkResource or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.PrivateLinkResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PrivateLinkResource] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + account_name=account_name, + group_name=group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PrivateLinkResource", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_database_accounts_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_database_accounts_operations.py index 9470fc5364e..74d32712b83 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_database_accounts_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_database_accounts_operations.py @@ -1,280 +1,280 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._restorable_database_accounts_operations import ( - build_get_by_location_request, - build_list_by_location_request, - build_list_request, -) - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class RestorableDatabaseAccountsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`restorable_database_accounts` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_by_location( - self, location: str, **kwargs: Any - ) -> AsyncIterable["_models.RestorableDatabaseAccountGetResult"]: - """Lists all the restorable Azure Cosmos DB database accounts available under the subscription and - in a region. This call requires - 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/read' permission. - - :param location: Cosmos DB region, with spaces between words and each word capitalized. - Required. - :type location: str - :return: An iterator like instance of either RestorableDatabaseAccountGetResult or the result - of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.RestorableDatabaseAccountGetResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.RestorableDatabaseAccountsListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_by_location_request( - location=location, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("RestorableDatabaseAccountsListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list(self, **kwargs: Any) -> AsyncIterable["_models.RestorableDatabaseAccountGetResult"]: - """Lists all the restorable Azure Cosmos DB database accounts available under the subscription. - This call requires 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/read' permission. - - :return: An iterator like instance of either RestorableDatabaseAccountGetResult or the result - of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.RestorableDatabaseAccountGetResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.RestorableDatabaseAccountsListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("RestorableDatabaseAccountsListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get_by_location( - self, location: str, instance_id: str, **kwargs: Any - ) -> _models.RestorableDatabaseAccountGetResult: - """Retrieves the properties of an existing Azure Cosmos DB restorable database account. This call - requires 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/read/*' permission. - - :param location: Cosmos DB region, with spaces between words and each word capitalized. - Required. - :type location: str - :param instance_id: The instanceId GUID of a restorable database account. Required. - :type instance_id: str - :return: RestorableDatabaseAccountGetResult or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.RestorableDatabaseAccountGetResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.RestorableDatabaseAccountGetResult] = kwargs.pop("cls", None) - - _request = build_get_by_location_request( - location=location, - instance_id=instance_id, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("RestorableDatabaseAccountGetResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._restorable_database_accounts_operations import ( + build_get_by_location_request, + build_list_by_location_request, + build_list_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class RestorableDatabaseAccountsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`restorable_database_accounts` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_by_location( + self, location: str, **kwargs: Any + ) -> AsyncIterable["_models.RestorableDatabaseAccountGetResult"]: + """Lists all the restorable Azure Cosmos DB database accounts available under the subscription and + in a region. This call requires + 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/read' permission. + + :param location: Cosmos DB region, with spaces between words and each word capitalized. + Required. + :type location: str + :return: An iterator like instance of either RestorableDatabaseAccountGetResult or the result + of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.RestorableDatabaseAccountGetResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RestorableDatabaseAccountsListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_location_request( + location=location, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RestorableDatabaseAccountsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.RestorableDatabaseAccountGetResult"]: + """Lists all the restorable Azure Cosmos DB database accounts available under the subscription. + This call requires 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/read' permission. + + :return: An iterator like instance of either RestorableDatabaseAccountGetResult or the result + of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.RestorableDatabaseAccountGetResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RestorableDatabaseAccountsListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RestorableDatabaseAccountsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get_by_location( + self, location: str, instance_id: str, **kwargs: Any + ) -> _models.RestorableDatabaseAccountGetResult: + """Retrieves the properties of an existing Azure Cosmos DB restorable database account. This call + requires 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/read/*' permission. + + :param location: Cosmos DB region, with spaces between words and each word capitalized. + Required. + :type location: str + :param instance_id: The instanceId GUID of a restorable database account. Required. + :type instance_id: str + :return: RestorableDatabaseAccountGetResult or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.RestorableDatabaseAccountGetResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RestorableDatabaseAccountGetResult] = kwargs.pop("cls", None) + + _request = build_get_by_location_request( + location=location, + instance_id=instance_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RestorableDatabaseAccountGetResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_gremlin_databases_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_gremlin_databases_operations.py index 20b36723dd2..e20776bddcb 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_gremlin_databases_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_gremlin_databases_operations.py @@ -1,144 +1,144 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._restorable_gremlin_databases_operations import build_list_request - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class RestorableGremlinDatabasesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`restorable_gremlin_databases` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, location: str, instance_id: str, **kwargs: Any - ) -> AsyncIterable["_models.RestorableGremlinDatabaseGetResult"]: - """Show the event feed of all mutations done on all the Azure Cosmos DB Gremlin databases under - the restorable account. This helps in scenario where database was accidentally deleted to get - the deletion time. This API requires - 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. - - :param location: Cosmos DB region, with spaces between words and each word capitalized. - Required. - :type location: str - :param instance_id: The instanceId GUID of a restorable database account. Required. - :type instance_id: str - :return: An iterator like instance of either RestorableGremlinDatabaseGetResult or the result - of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.RestorableGremlinDatabaseGetResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.RestorableGremlinDatabasesListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - location=location, - instance_id=instance_id, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("RestorableGremlinDatabasesListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._restorable_gremlin_databases_operations import build_list_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class RestorableGremlinDatabasesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`restorable_gremlin_databases` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, location: str, instance_id: str, **kwargs: Any + ) -> AsyncIterable["_models.RestorableGremlinDatabaseGetResult"]: + """Show the event feed of all mutations done on all the Azure Cosmos DB Gremlin databases under + the restorable account. This helps in scenario where database was accidentally deleted to get + the deletion time. This API requires + 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. + + :param location: Cosmos DB region, with spaces between words and each word capitalized. + Required. + :type location: str + :param instance_id: The instanceId GUID of a restorable database account. Required. + :type instance_id: str + :return: An iterator like instance of either RestorableGremlinDatabaseGetResult or the result + of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.RestorableGremlinDatabaseGetResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RestorableGremlinDatabasesListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + location=location, + instance_id=instance_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RestorableGremlinDatabasesListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_gremlin_graphs_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_gremlin_graphs_operations.py index 252e0b6440c..9727d2e9c26 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_gremlin_graphs_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_gremlin_graphs_operations.py @@ -1,159 +1,159 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._restorable_gremlin_graphs_operations import build_list_request - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class RestorableGremlinGraphsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`restorable_gremlin_graphs` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, - location: str, - instance_id: str, - restorable_gremlin_database_rid: Optional[str] = None, - start_time: Optional[str] = None, - end_time: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RestorableGremlinGraphGetResult"]: - """Show the event feed of all mutations done on all the Azure Cosmos DB Gremlin graphs under a - specific database. This helps in scenario where container was accidentally deleted. This API - requires 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. - - :param location: Cosmos DB region, with spaces between words and each word capitalized. - Required. - :type location: str - :param instance_id: The instanceId GUID of a restorable database account. Required. - :type instance_id: str - :param restorable_gremlin_database_rid: The resource ID of the Gremlin database. Default value - is None. - :type restorable_gremlin_database_rid: str - :param start_time: Restorable Gremlin graphs event feed start time. Default value is None. - :type start_time: str - :param end_time: Restorable Gremlin graphs event feed end time. Default value is None. - :type end_time: str - :return: An iterator like instance of either RestorableGremlinGraphGetResult or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.RestorableGremlinGraphGetResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.RestorableGremlinGraphsListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - location=location, - instance_id=instance_id, - subscription_id=self._config.subscription_id, - restorable_gremlin_database_rid=restorable_gremlin_database_rid, - start_time=start_time, - end_time=end_time, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("RestorableGremlinGraphsListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._restorable_gremlin_graphs_operations import build_list_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class RestorableGremlinGraphsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`restorable_gremlin_graphs` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, + location: str, + instance_id: str, + restorable_gremlin_database_rid: Optional[str] = None, + start_time: Optional[str] = None, + end_time: Optional[str] = None, + **kwargs: Any + ) -> AsyncIterable["_models.RestorableGremlinGraphGetResult"]: + """Show the event feed of all mutations done on all the Azure Cosmos DB Gremlin graphs under a + specific database. This helps in scenario where container was accidentally deleted. This API + requires 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. + + :param location: Cosmos DB region, with spaces between words and each word capitalized. + Required. + :type location: str + :param instance_id: The instanceId GUID of a restorable database account. Required. + :type instance_id: str + :param restorable_gremlin_database_rid: The resource ID of the Gremlin database. Default value + is None. + :type restorable_gremlin_database_rid: str + :param start_time: Restorable Gremlin graphs event feed start time. Default value is None. + :type start_time: str + :param end_time: Restorable Gremlin graphs event feed end time. Default value is None. + :type end_time: str + :return: An iterator like instance of either RestorableGremlinGraphGetResult or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.RestorableGremlinGraphGetResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RestorableGremlinGraphsListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + location=location, + instance_id=instance_id, + subscription_id=self._config.subscription_id, + restorable_gremlin_database_rid=restorable_gremlin_database_rid, + start_time=start_time, + end_time=end_time, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RestorableGremlinGraphsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_gremlin_resources_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_gremlin_resources_operations.py index ed6fb291b2a..bed6e396aa7 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_gremlin_resources_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_gremlin_resources_operations.py @@ -1,157 +1,157 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._restorable_gremlin_resources_operations import build_list_request - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class RestorableGremlinResourcesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`restorable_gremlin_resources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, - location: str, - instance_id: str, - restore_location: Optional[str] = None, - restore_timestamp_in_utc: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RestorableGremlinResourcesGetResult"]: - """Return a list of gremlin database and graphs combo that exist on the account at the given - timestamp and location. This helps in scenarios to validate what resources exist at given - timestamp and location. This API requires - 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. - - :param location: Cosmos DB region, with spaces between words and each word capitalized. - Required. - :type location: str - :param instance_id: The instanceId GUID of a restorable database account. Required. - :type instance_id: str - :param restore_location: The location where the restorable resources are located. Default value - is None. - :type restore_location: str - :param restore_timestamp_in_utc: The timestamp when the restorable resources existed. Default - value is None. - :type restore_timestamp_in_utc: str - :return: An iterator like instance of either RestorableGremlinResourcesGetResult or the result - of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.RestorableGremlinResourcesGetResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.RestorableGremlinResourcesListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - location=location, - instance_id=instance_id, - subscription_id=self._config.subscription_id, - restore_location=restore_location, - restore_timestamp_in_utc=restore_timestamp_in_utc, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("RestorableGremlinResourcesListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._restorable_gremlin_resources_operations import build_list_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class RestorableGremlinResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`restorable_gremlin_resources` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, + location: str, + instance_id: str, + restore_location: Optional[str] = None, + restore_timestamp_in_utc: Optional[str] = None, + **kwargs: Any + ) -> AsyncIterable["_models.RestorableGremlinResourcesGetResult"]: + """Return a list of gremlin database and graphs combo that exist on the account at the given + timestamp and location. This helps in scenarios to validate what resources exist at given + timestamp and location. This API requires + 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. + + :param location: Cosmos DB region, with spaces between words and each word capitalized. + Required. + :type location: str + :param instance_id: The instanceId GUID of a restorable database account. Required. + :type instance_id: str + :param restore_location: The location where the restorable resources are located. Default value + is None. + :type restore_location: str + :param restore_timestamp_in_utc: The timestamp when the restorable resources existed. Default + value is None. + :type restore_timestamp_in_utc: str + :return: An iterator like instance of either RestorableGremlinResourcesGetResult or the result + of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.RestorableGremlinResourcesGetResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RestorableGremlinResourcesListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + location=location, + instance_id=instance_id, + subscription_id=self._config.subscription_id, + restore_location=restore_location, + restore_timestamp_in_utc=restore_timestamp_in_utc, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RestorableGremlinResourcesListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_mongodb_collections_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_mongodb_collections_operations.py index caaa24fe1e0..53fbdd05a92 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_mongodb_collections_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_mongodb_collections_operations.py @@ -1,159 +1,159 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._restorable_mongodb_collections_operations import build_list_request - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class RestorableMongodbCollectionsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`restorable_mongodb_collections` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, - location: str, - instance_id: str, - restorable_mongodb_database_rid: Optional[str] = None, - start_time: Optional[str] = None, - end_time: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RestorableMongodbCollectionGetResult"]: - """Show the event feed of all mutations done on all the Azure Cosmos DB MongoDB collections under - a specific database. This helps in scenario where container was accidentally deleted. This - API requires 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. - - :param location: Cosmos DB region, with spaces between words and each word capitalized. - Required. - :type location: str - :param instance_id: The instanceId GUID of a restorable database account. Required. - :type instance_id: str - :param restorable_mongodb_database_rid: The resource ID of the MongoDB database. Default value - is None. - :type restorable_mongodb_database_rid: str - :param start_time: Restorable MongoDB collections event feed start time. Default value is None. - :type start_time: str - :param end_time: Restorable MongoDB collections event feed end time. Default value is None. - :type end_time: str - :return: An iterator like instance of either RestorableMongodbCollectionGetResult or the result - of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.RestorableMongodbCollectionGetResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.RestorableMongodbCollectionsListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - location=location, - instance_id=instance_id, - subscription_id=self._config.subscription_id, - restorable_mongodb_database_rid=restorable_mongodb_database_rid, - start_time=start_time, - end_time=end_time, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("RestorableMongodbCollectionsListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._restorable_mongodb_collections_operations import build_list_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class RestorableMongodbCollectionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`restorable_mongodb_collections` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, + location: str, + instance_id: str, + restorable_mongodb_database_rid: Optional[str] = None, + start_time: Optional[str] = None, + end_time: Optional[str] = None, + **kwargs: Any + ) -> AsyncIterable["_models.RestorableMongodbCollectionGetResult"]: + """Show the event feed of all mutations done on all the Azure Cosmos DB MongoDB collections under + a specific database. This helps in scenario where container was accidentally deleted. This + API requires 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. + + :param location: Cosmos DB region, with spaces between words and each word capitalized. + Required. + :type location: str + :param instance_id: The instanceId GUID of a restorable database account. Required. + :type instance_id: str + :param restorable_mongodb_database_rid: The resource ID of the MongoDB database. Default value + is None. + :type restorable_mongodb_database_rid: str + :param start_time: Restorable MongoDB collections event feed start time. Default value is None. + :type start_time: str + :param end_time: Restorable MongoDB collections event feed end time. Default value is None. + :type end_time: str + :return: An iterator like instance of either RestorableMongodbCollectionGetResult or the result + of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.RestorableMongodbCollectionGetResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RestorableMongodbCollectionsListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + location=location, + instance_id=instance_id, + subscription_id=self._config.subscription_id, + restorable_mongodb_database_rid=restorable_mongodb_database_rid, + start_time=start_time, + end_time=end_time, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RestorableMongodbCollectionsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_mongodb_databases_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_mongodb_databases_operations.py index 75cc846595b..e8696dcf1c0 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_mongodb_databases_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_mongodb_databases_operations.py @@ -1,144 +1,144 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._restorable_mongodb_databases_operations import build_list_request - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class RestorableMongodbDatabasesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`restorable_mongodb_databases` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, location: str, instance_id: str, **kwargs: Any - ) -> AsyncIterable["_models.RestorableMongodbDatabaseGetResult"]: - """Show the event feed of all mutations done on all the Azure Cosmos DB MongoDB databases under - the restorable account. This helps in scenario where database was accidentally deleted to get - the deletion time. This API requires - 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. - - :param location: Cosmos DB region, with spaces between words and each word capitalized. - Required. - :type location: str - :param instance_id: The instanceId GUID of a restorable database account. Required. - :type instance_id: str - :return: An iterator like instance of either RestorableMongodbDatabaseGetResult or the result - of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.RestorableMongodbDatabaseGetResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.RestorableMongodbDatabasesListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - location=location, - instance_id=instance_id, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("RestorableMongodbDatabasesListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._restorable_mongodb_databases_operations import build_list_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class RestorableMongodbDatabasesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`restorable_mongodb_databases` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, location: str, instance_id: str, **kwargs: Any + ) -> AsyncIterable["_models.RestorableMongodbDatabaseGetResult"]: + """Show the event feed of all mutations done on all the Azure Cosmos DB MongoDB databases under + the restorable account. This helps in scenario where database was accidentally deleted to get + the deletion time. This API requires + 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. + + :param location: Cosmos DB region, with spaces between words and each word capitalized. + Required. + :type location: str + :param instance_id: The instanceId GUID of a restorable database account. Required. + :type instance_id: str + :return: An iterator like instance of either RestorableMongodbDatabaseGetResult or the result + of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.RestorableMongodbDatabaseGetResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RestorableMongodbDatabasesListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + location=location, + instance_id=instance_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RestorableMongodbDatabasesListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_mongodb_resources_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_mongodb_resources_operations.py index a3d926fcb6e..3bd82fca524 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_mongodb_resources_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_mongodb_resources_operations.py @@ -1,157 +1,157 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._restorable_mongodb_resources_operations import build_list_request - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class RestorableMongodbResourcesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`restorable_mongodb_resources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, - location: str, - instance_id: str, - restore_location: Optional[str] = None, - restore_timestamp_in_utc: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RestorableMongodbResourcesGetResult"]: - """Return a list of database and collection combo that exist on the account at the given timestamp - and location. This helps in scenarios to validate what resources exist at given timestamp and - location. This API requires - 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. - - :param location: Cosmos DB region, with spaces between words and each word capitalized. - Required. - :type location: str - :param instance_id: The instanceId GUID of a restorable database account. Required. - :type instance_id: str - :param restore_location: The location where the restorable resources are located. Default value - is None. - :type restore_location: str - :param restore_timestamp_in_utc: The timestamp when the restorable resources existed. Default - value is None. - :type restore_timestamp_in_utc: str - :return: An iterator like instance of either RestorableMongodbResourcesGetResult or the result - of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.RestorableMongodbResourcesGetResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.RestorableMongodbResourcesListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - location=location, - instance_id=instance_id, - subscription_id=self._config.subscription_id, - restore_location=restore_location, - restore_timestamp_in_utc=restore_timestamp_in_utc, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("RestorableMongodbResourcesListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._restorable_mongodb_resources_operations import build_list_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class RestorableMongodbResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`restorable_mongodb_resources` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, + location: str, + instance_id: str, + restore_location: Optional[str] = None, + restore_timestamp_in_utc: Optional[str] = None, + **kwargs: Any + ) -> AsyncIterable["_models.RestorableMongodbResourcesGetResult"]: + """Return a list of database and collection combo that exist on the account at the given timestamp + and location. This helps in scenarios to validate what resources exist at given timestamp and + location. This API requires + 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. + + :param location: Cosmos DB region, with spaces between words and each word capitalized. + Required. + :type location: str + :param instance_id: The instanceId GUID of a restorable database account. Required. + :type instance_id: str + :param restore_location: The location where the restorable resources are located. Default value + is None. + :type restore_location: str + :param restore_timestamp_in_utc: The timestamp when the restorable resources existed. Default + value is None. + :type restore_timestamp_in_utc: str + :return: An iterator like instance of either RestorableMongodbResourcesGetResult or the result + of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.RestorableMongodbResourcesGetResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RestorableMongodbResourcesListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + location=location, + instance_id=instance_id, + subscription_id=self._config.subscription_id, + restore_location=restore_location, + restore_timestamp_in_utc=restore_timestamp_in_utc, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RestorableMongodbResourcesListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_sql_containers_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_sql_containers_operations.py index 5cac3ed0005..38f893922e0 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_sql_containers_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_sql_containers_operations.py @@ -1,158 +1,158 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._restorable_sql_containers_operations import build_list_request - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class RestorableSqlContainersOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`restorable_sql_containers` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, - location: str, - instance_id: str, - restorable_sql_database_rid: Optional[str] = None, - start_time: Optional[str] = None, - end_time: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RestorableSqlContainerGetResult"]: - """Show the event feed of all mutations done on all the Azure Cosmos DB SQL containers under a - specific database. This helps in scenario where container was accidentally deleted. This API - requires 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. - - :param location: Cosmos DB region, with spaces between words and each word capitalized. - Required. - :type location: str - :param instance_id: The instanceId GUID of a restorable database account. Required. - :type instance_id: str - :param restorable_sql_database_rid: The resource ID of the SQL database. Default value is None. - :type restorable_sql_database_rid: str - :param start_time: Restorable Sql containers event feed start time. Default value is None. - :type start_time: str - :param end_time: Restorable Sql containers event feed end time. Default value is None. - :type end_time: str - :return: An iterator like instance of either RestorableSqlContainerGetResult or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.RestorableSqlContainerGetResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.RestorableSqlContainersListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - location=location, - instance_id=instance_id, - subscription_id=self._config.subscription_id, - restorable_sql_database_rid=restorable_sql_database_rid, - start_time=start_time, - end_time=end_time, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("RestorableSqlContainersListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._restorable_sql_containers_operations import build_list_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class RestorableSqlContainersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`restorable_sql_containers` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, + location: str, + instance_id: str, + restorable_sql_database_rid: Optional[str] = None, + start_time: Optional[str] = None, + end_time: Optional[str] = None, + **kwargs: Any + ) -> AsyncIterable["_models.RestorableSqlContainerGetResult"]: + """Show the event feed of all mutations done on all the Azure Cosmos DB SQL containers under a + specific database. This helps in scenario where container was accidentally deleted. This API + requires 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. + + :param location: Cosmos DB region, with spaces between words and each word capitalized. + Required. + :type location: str + :param instance_id: The instanceId GUID of a restorable database account. Required. + :type instance_id: str + :param restorable_sql_database_rid: The resource ID of the SQL database. Default value is None. + :type restorable_sql_database_rid: str + :param start_time: Restorable Sql containers event feed start time. Default value is None. + :type start_time: str + :param end_time: Restorable Sql containers event feed end time. Default value is None. + :type end_time: str + :return: An iterator like instance of either RestorableSqlContainerGetResult or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.RestorableSqlContainerGetResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RestorableSqlContainersListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + location=location, + instance_id=instance_id, + subscription_id=self._config.subscription_id, + restorable_sql_database_rid=restorable_sql_database_rid, + start_time=start_time, + end_time=end_time, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RestorableSqlContainersListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_sql_databases_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_sql_databases_operations.py index e56c5069eb7..bfb7c3f659c 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_sql_databases_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_sql_databases_operations.py @@ -1,144 +1,144 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._restorable_sql_databases_operations import build_list_request - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class RestorableSqlDatabasesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`restorable_sql_databases` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, location: str, instance_id: str, **kwargs: Any - ) -> AsyncIterable["_models.RestorableSqlDatabaseGetResult"]: - """Show the event feed of all mutations done on all the Azure Cosmos DB SQL databases under the - restorable account. This helps in scenario where database was accidentally deleted to get the - deletion time. This API requires - 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. - - :param location: Cosmos DB region, with spaces between words and each word capitalized. - Required. - :type location: str - :param instance_id: The instanceId GUID of a restorable database account. Required. - :type instance_id: str - :return: An iterator like instance of either RestorableSqlDatabaseGetResult or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.RestorableSqlDatabaseGetResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.RestorableSqlDatabasesListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - location=location, - instance_id=instance_id, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("RestorableSqlDatabasesListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._restorable_sql_databases_operations import build_list_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class RestorableSqlDatabasesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`restorable_sql_databases` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, location: str, instance_id: str, **kwargs: Any + ) -> AsyncIterable["_models.RestorableSqlDatabaseGetResult"]: + """Show the event feed of all mutations done on all the Azure Cosmos DB SQL databases under the + restorable account. This helps in scenario where database was accidentally deleted to get the + deletion time. This API requires + 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. + + :param location: Cosmos DB region, with spaces between words and each word capitalized. + Required. + :type location: str + :param instance_id: The instanceId GUID of a restorable database account. Required. + :type instance_id: str + :return: An iterator like instance of either RestorableSqlDatabaseGetResult or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.RestorableSqlDatabaseGetResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RestorableSqlDatabasesListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + location=location, + instance_id=instance_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RestorableSqlDatabasesListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_sql_resources_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_sql_resources_operations.py index 2711870bf62..18589426021 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_sql_resources_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_sql_resources_operations.py @@ -1,157 +1,157 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._restorable_sql_resources_operations import build_list_request - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class RestorableSqlResourcesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`restorable_sql_resources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, - location: str, - instance_id: str, - restore_location: Optional[str] = None, - restore_timestamp_in_utc: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RestorableSqlResourcesGetResult"]: - """Return a list of database and container combo that exist on the account at the given timestamp - and location. This helps in scenarios to validate what resources exist at given timestamp and - location. This API requires - 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. - - :param location: Cosmos DB region, with spaces between words and each word capitalized. - Required. - :type location: str - :param instance_id: The instanceId GUID of a restorable database account. Required. - :type instance_id: str - :param restore_location: The location where the restorable resources are located. Default value - is None. - :type restore_location: str - :param restore_timestamp_in_utc: The timestamp when the restorable resources existed. Default - value is None. - :type restore_timestamp_in_utc: str - :return: An iterator like instance of either RestorableSqlResourcesGetResult or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.RestorableSqlResourcesGetResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.RestorableSqlResourcesListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - location=location, - instance_id=instance_id, - subscription_id=self._config.subscription_id, - restore_location=restore_location, - restore_timestamp_in_utc=restore_timestamp_in_utc, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("RestorableSqlResourcesListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._restorable_sql_resources_operations import build_list_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class RestorableSqlResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`restorable_sql_resources` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, + location: str, + instance_id: str, + restore_location: Optional[str] = None, + restore_timestamp_in_utc: Optional[str] = None, + **kwargs: Any + ) -> AsyncIterable["_models.RestorableSqlResourcesGetResult"]: + """Return a list of database and container combo that exist on the account at the given timestamp + and location. This helps in scenarios to validate what resources exist at given timestamp and + location. This API requires + 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. + + :param location: Cosmos DB region, with spaces between words and each word capitalized. + Required. + :type location: str + :param instance_id: The instanceId GUID of a restorable database account. Required. + :type instance_id: str + :param restore_location: The location where the restorable resources are located. Default value + is None. + :type restore_location: str + :param restore_timestamp_in_utc: The timestamp when the restorable resources existed. Default + value is None. + :type restore_timestamp_in_utc: str + :return: An iterator like instance of either RestorableSqlResourcesGetResult or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.RestorableSqlResourcesGetResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RestorableSqlResourcesListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + location=location, + instance_id=instance_id, + subscription_id=self._config.subscription_id, + restore_location=restore_location, + restore_timestamp_in_utc=restore_timestamp_in_utc, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RestorableSqlResourcesListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_table_resources_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_table_resources_operations.py index 8f0fc409ba5..45f0907202c 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_table_resources_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_table_resources_operations.py @@ -1,156 +1,156 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._restorable_table_resources_operations import build_list_request - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class RestorableTableResourcesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`restorable_table_resources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, - location: str, - instance_id: str, - restore_location: Optional[str] = None, - restore_timestamp_in_utc: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RestorableTableResourcesGetResult"]: - """Return a list of tables that exist on the account at the given timestamp and location. This - helps in scenarios to validate what resources exist at given timestamp and location. This API - requires 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. - - :param location: Cosmos DB region, with spaces between words and each word capitalized. - Required. - :type location: str - :param instance_id: The instanceId GUID of a restorable database account. Required. - :type instance_id: str - :param restore_location: The location where the restorable resources are located. Default value - is None. - :type restore_location: str - :param restore_timestamp_in_utc: The timestamp when the restorable resources existed. Default - value is None. - :type restore_timestamp_in_utc: str - :return: An iterator like instance of either RestorableTableResourcesGetResult or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.RestorableTableResourcesGetResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.RestorableTableResourcesListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - location=location, - instance_id=instance_id, - subscription_id=self._config.subscription_id, - restore_location=restore_location, - restore_timestamp_in_utc=restore_timestamp_in_utc, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("RestorableTableResourcesListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._restorable_table_resources_operations import build_list_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class RestorableTableResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`restorable_table_resources` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, + location: str, + instance_id: str, + restore_location: Optional[str] = None, + restore_timestamp_in_utc: Optional[str] = None, + **kwargs: Any + ) -> AsyncIterable["_models.RestorableTableResourcesGetResult"]: + """Return a list of tables that exist on the account at the given timestamp and location. This + helps in scenarios to validate what resources exist at given timestamp and location. This API + requires 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. + + :param location: Cosmos DB region, with spaces between words and each word capitalized. + Required. + :type location: str + :param instance_id: The instanceId GUID of a restorable database account. Required. + :type instance_id: str + :param restore_location: The location where the restorable resources are located. Default value + is None. + :type restore_location: str + :param restore_timestamp_in_utc: The timestamp when the restorable resources existed. Default + value is None. + :type restore_timestamp_in_utc: str + :return: An iterator like instance of either RestorableTableResourcesGetResult or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.RestorableTableResourcesGetResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RestorableTableResourcesListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + location=location, + instance_id=instance_id, + subscription_id=self._config.subscription_id, + restore_location=restore_location, + restore_timestamp_in_utc=restore_timestamp_in_utc, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RestorableTableResourcesListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_tables_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_tables_operations.py index 9b618100216..868a6a90b92 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_tables_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_restorable_tables_operations.py @@ -1,154 +1,154 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._restorable_tables_operations import build_list_request - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class RestorableTablesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`restorable_tables` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, - location: str, - instance_id: str, - start_time: Optional[str] = None, - end_time: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RestorableTableGetResult"]: - """Show the event feed of all mutations done on all the Azure Cosmos DB Tables. This helps in - scenario where table was accidentally deleted. This API requires - 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. - - :param location: Cosmos DB region, with spaces between words and each word capitalized. - Required. - :type location: str - :param instance_id: The instanceId GUID of a restorable database account. Required. - :type instance_id: str - :param start_time: Restorable Tables event feed start time. Default value is None. - :type start_time: str - :param end_time: Restorable Tables event feed end time. Default value is None. - :type end_time: str - :return: An iterator like instance of either RestorableTableGetResult or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.RestorableTableGetResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.RestorableTablesListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - location=location, - instance_id=instance_id, - subscription_id=self._config.subscription_id, - start_time=start_time, - end_time=end_time, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("RestorableTablesListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._restorable_tables_operations import build_list_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class RestorableTablesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`restorable_tables` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, + location: str, + instance_id: str, + start_time: Optional[str] = None, + end_time: Optional[str] = None, + **kwargs: Any + ) -> AsyncIterable["_models.RestorableTableGetResult"]: + """Show the event feed of all mutations done on all the Azure Cosmos DB Tables. This helps in + scenario where table was accidentally deleted. This API requires + 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. + + :param location: Cosmos DB region, with spaces between words and each word capitalized. + Required. + :type location: str + :param instance_id: The instanceId GUID of a restorable database account. Required. + :type instance_id: str + :param start_time: Restorable Tables event feed start time. Default value is None. + :type start_time: str + :param end_time: Restorable Tables event feed end time. Default value is None. + :type end_time: str + :return: An iterator like instance of either RestorableTableGetResult or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.RestorableTableGetResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RestorableTablesListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + location=location, + instance_id=instance_id, + subscription_id=self._config.subscription_id, + start_time=start_time, + end_time=end_time, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RestorableTablesListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_service_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_service_operations.py index 768b0fc604e..89512c0ae49 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_service_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_service_operations.py @@ -1,532 +1,532 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling - -from ... import models as _models -from ...operations._service_operations import ( - build_create_request, - build_delete_request, - build_get_request, - build_list_request, -) - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class ServiceOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`service` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> AsyncIterable["_models.ServiceResource"]: - """Gets the status of service. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either ServiceResource or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.ServiceResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ServiceResourceListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("ServiceResourceListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - async def _create_initial( - self, - resource_group_name: str, - account_name: str, - service_name: str, - create_update_parameters: Union[_models.ServiceResourceCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_parameters, (IOBase, bytes)): - _content = create_update_parameters - else: - _json = self._serialize.body(create_update_parameters, "ServiceResourceCreateUpdateParameters") - - _request = build_create_request( - resource_group_name=resource_group_name, - account_name=account_name, - service_name=service_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create( - self, - resource_group_name: str, - account_name: str, - service_name: str, - create_update_parameters: _models.ServiceResourceCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ServiceResource]: - """Creates a service. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param service_name: Cosmos DB service name. Required. - :type service_name: str - :param create_update_parameters: The Service resource parameters. Required. - :type create_update_parameters: - ~azure.mgmt.cosmosdb.models.ServiceResourceCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ServiceResource or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ServiceResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create( - self, - resource_group_name: str, - account_name: str, - service_name: str, - create_update_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ServiceResource]: - """Creates a service. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param service_name: Cosmos DB service name. Required. - :type service_name: str - :param create_update_parameters: The Service resource parameters. Required. - :type create_update_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ServiceResource or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ServiceResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create( - self, - resource_group_name: str, - account_name: str, - service_name: str, - create_update_parameters: Union[_models.ServiceResourceCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.ServiceResource]: - """Creates a service. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param service_name: Cosmos DB service name. Required. - :type service_name: str - :param create_update_parameters: The Service resource parameters. Is either a - ServiceResourceCreateUpdateParameters type or a IO[bytes] type. Required. - :type create_update_parameters: - ~azure.mgmt.cosmosdb.models.ServiceResourceCreateUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either ServiceResource or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ServiceResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ServiceResource] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_initial( - resource_group_name=resource_group_name, - account_name=account_name, - service_name=service_name, - create_update_parameters=create_update_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ServiceResource", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ServiceResource].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ServiceResource]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @distributed_trace_async - async def get( - self, resource_group_name: str, account_name: str, service_name: str, **kwargs: Any - ) -> _models.ServiceResource: - """Gets the status of service. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param service_name: Cosmos DB service name. Required. - :type service_name: str - :return: ServiceResource or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ServiceResource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ServiceResource] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - account_name=account_name, - service_name=service_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ServiceResource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _delete_initial( - self, resource_group_name: str, account_name: str, service_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - account_name=account_name, - service_name=service_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202, 204]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete( - self, resource_group_name: str, account_name: str, service_name: str, **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes service with the given serviceName. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param service_name: Cosmos DB service name. Required. - :type service_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_initial( - resource_group_name=resource_group_name, - account_name=account_name, - service_name=service_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ...operations._service_operations import ( + build_create_request, + build_delete_request, + build_get_request, + build_list_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class ServiceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`service` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> AsyncIterable["_models.ServiceResource"]: + """Gets the status of service. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either ServiceResource or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.ServiceResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ServiceResourceListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ServiceResourceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + async def _create_initial( + self, + resource_group_name: str, + account_name: str, + service_name: str, + create_update_parameters: Union[_models.ServiceResourceCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_parameters, (IOBase, bytes)): + _content = create_update_parameters + else: + _json = self._serialize.body(create_update_parameters, "ServiceResourceCreateUpdateParameters") + + _request = build_create_request( + resource_group_name=resource_group_name, + account_name=account_name, + service_name=service_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create( + self, + resource_group_name: str, + account_name: str, + service_name: str, + create_update_parameters: _models.ServiceResourceCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ServiceResource]: + """Creates a service. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param service_name: Cosmos DB service name. Required. + :type service_name: str + :param create_update_parameters: The Service resource parameters. Required. + :type create_update_parameters: + ~azure.mgmt.cosmosdb.models.ServiceResourceCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ServiceResource or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ServiceResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create( + self, + resource_group_name: str, + account_name: str, + service_name: str, + create_update_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ServiceResource]: + """Creates a service. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param service_name: Cosmos DB service name. Required. + :type service_name: str + :param create_update_parameters: The Service resource parameters. Required. + :type create_update_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ServiceResource or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ServiceResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create( + self, + resource_group_name: str, + account_name: str, + service_name: str, + create_update_parameters: Union[_models.ServiceResourceCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.ServiceResource]: + """Creates a service. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param service_name: Cosmos DB service name. Required. + :type service_name: str + :param create_update_parameters: The Service resource parameters. Is either a + ServiceResourceCreateUpdateParameters type or a IO[bytes] type. Required. + :type create_update_parameters: + ~azure.mgmt.cosmosdb.models.ServiceResourceCreateUpdateParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either ServiceResource or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ServiceResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ServiceResource] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_initial( + resource_group_name=resource_group_name, + account_name=account_name, + service_name=service_name, + create_update_parameters=create_update_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ServiceResource", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ServiceResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ServiceResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace_async + async def get( + self, resource_group_name: str, account_name: str, service_name: str, **kwargs: Any + ) -> _models.ServiceResource: + """Gets the status of service. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param service_name: Cosmos DB service name. Required. + :type service_name: str + :return: ServiceResource or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ServiceResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ServiceResource] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + account_name=account_name, + service_name=service_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ServiceResource", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _delete_initial( + self, resource_group_name: str, account_name: str, service_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + account_name=account_name, + service_name=service_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete( + self, resource_group_name: str, account_name: str, service_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes service with the given serviceName. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param service_name: Cosmos DB service name. Required. + :type service_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + account_name=account_name, + service_name=service_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_sql_resources_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_sql_resources_operations.py index c9f5772f1d4..a068d20daeb 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_sql_resources_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_sql_resources_operations.py @@ -1,6689 +1,6689 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling - -from ... import models as _models -from ...operations._sql_resources_operations import ( - build_create_update_client_encryption_key_request, - build_create_update_sql_container_request, - build_create_update_sql_database_request, - build_create_update_sql_role_assignment_request, - build_create_update_sql_role_definition_request, - build_create_update_sql_stored_procedure_request, - build_create_update_sql_trigger_request, - build_create_update_sql_user_defined_function_request, - build_delete_sql_container_request, - build_delete_sql_database_request, - build_delete_sql_role_assignment_request, - build_delete_sql_role_definition_request, - build_delete_sql_stored_procedure_request, - build_delete_sql_trigger_request, - build_delete_sql_user_defined_function_request, - build_get_client_encryption_key_request, - build_get_sql_container_request, - build_get_sql_container_throughput_request, - build_get_sql_database_request, - build_get_sql_database_throughput_request, - build_get_sql_role_assignment_request, - build_get_sql_role_definition_request, - build_get_sql_stored_procedure_request, - build_get_sql_trigger_request, - build_get_sql_user_defined_function_request, - build_list_client_encryption_keys_request, - build_list_sql_container_partition_merge_request, - build_list_sql_containers_request, - build_list_sql_databases_request, - build_list_sql_role_assignments_request, - build_list_sql_role_definitions_request, - build_list_sql_stored_procedures_request, - build_list_sql_triggers_request, - build_list_sql_user_defined_functions_request, - build_migrate_sql_container_to_autoscale_request, - build_migrate_sql_container_to_manual_throughput_request, - build_migrate_sql_database_to_autoscale_request, - build_migrate_sql_database_to_manual_throughput_request, - build_retrieve_continuous_backup_information_request, - build_sql_container_redistribute_throughput_request, - build_sql_container_retrieve_throughput_distribution_request, - build_sql_database_partition_merge_request, - build_sql_database_redistribute_throughput_request, - build_sql_database_retrieve_throughput_distribution_request, - build_update_sql_container_throughput_request, - build_update_sql_database_throughput_request, -) - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class SqlResourcesOperations: # pylint: disable=too-many-public-methods - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`sql_resources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_sql_databases( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> AsyncIterable["_models.SqlDatabaseGetResults"]: - """Lists the SQL databases under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either SqlDatabaseGetResults or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.SqlDatabaseGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SqlDatabaseListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_sql_databases_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("SqlDatabaseListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get_sql_database( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> _models.SqlDatabaseGetResults: - """Gets the SQL database under an existing Azure Cosmos DB database account with the provided - name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: SqlDatabaseGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.SqlDatabaseGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SqlDatabaseGetResults] = kwargs.pop("cls", None) - - _request = build_get_sql_database_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("SqlDatabaseGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _create_update_sql_database_initial( - self, - resource_group_name: str, - account_name: str, - database_name: str, - create_update_sql_database_parameters: Union[_models.SqlDatabaseCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_sql_database_parameters, (IOBase, bytes)): - _content = create_update_sql_database_parameters - else: - _json = self._serialize.body(create_update_sql_database_parameters, "SqlDatabaseCreateUpdateParameters") - - _request = build_create_update_sql_database_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_update_sql_database( - self, - resource_group_name: str, - account_name: str, - database_name: str, - create_update_sql_database_parameters: _models.SqlDatabaseCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.SqlDatabaseGetResults]: - """Create or update an Azure Cosmos DB SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param create_update_sql_database_parameters: The parameters to provide for the current SQL - database. Required. - :type create_update_sql_database_parameters: - ~azure.mgmt.cosmosdb.models.SqlDatabaseCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either SqlDatabaseGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlDatabaseGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_update_sql_database( - self, - resource_group_name: str, - account_name: str, - database_name: str, - create_update_sql_database_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.SqlDatabaseGetResults]: - """Create or update an Azure Cosmos DB SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param create_update_sql_database_parameters: The parameters to provide for the current SQL - database. Required. - :type create_update_sql_database_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either SqlDatabaseGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlDatabaseGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_update_sql_database( - self, - resource_group_name: str, - account_name: str, - database_name: str, - create_update_sql_database_parameters: Union[_models.SqlDatabaseCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.SqlDatabaseGetResults]: - """Create or update an Azure Cosmos DB SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param create_update_sql_database_parameters: The parameters to provide for the current SQL - database. Is either a SqlDatabaseCreateUpdateParameters type or a IO[bytes] type. Required. - :type create_update_sql_database_parameters: - ~azure.mgmt.cosmosdb.models.SqlDatabaseCreateUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either SqlDatabaseGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlDatabaseGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SqlDatabaseGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_update_sql_database_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - create_update_sql_database_parameters=create_update_sql_database_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("SqlDatabaseGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.SqlDatabaseGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.SqlDatabaseGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _delete_sql_database_initial( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_sql_database_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete_sql_database( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes an existing Azure Cosmos DB SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_sql_database_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace_async - async def get_sql_database_throughput( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> _models.ThroughputSettingsGetResults: - """Gets the RUs per second of the SQL database under an existing Azure Cosmos DB database account - with the provided name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: ThroughputSettingsGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - - _request = build_get_sql_database_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _update_sql_database_throughput_initial( - self, - resource_group_name: str, - account_name: str, - database_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(update_throughput_parameters, (IOBase, bytes)): - _content = update_throughput_parameters - else: - _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") - - _request = build_update_sql_database_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_update_sql_database_throughput( - self, - resource_group_name: str, - account_name: str, - database_name: str, - update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param update_throughput_parameters: The parameters to provide for the RUs per second of the - current SQL database. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_update_sql_database_throughput( - self, - resource_group_name: str, - account_name: str, - database_name: str, - update_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param update_throughput_parameters: The parameters to provide for the RUs per second of the - current SQL database. Required. - :type update_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_update_sql_database_throughput( - self, - resource_group_name: str, - account_name: str, - database_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param update_throughput_parameters: The parameters to provide for the RUs per second of the - current SQL database. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] type. - Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._update_sql_database_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - update_throughput_parameters=update_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _migrate_sql_database_to_autoscale_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_sql_database_to_autoscale_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_migrate_sql_database_to_autoscale( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB SQL database from manual throughput to autoscale. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._migrate_sql_database_to_autoscale_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _migrate_sql_database_to_manual_throughput_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_sql_database_to_manual_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_migrate_sql_database_to_manual_throughput( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB SQL database from autoscale to manual throughput. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._migrate_sql_database_to_manual_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @distributed_trace - def list_client_encryption_keys( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> AsyncIterable["_models.ClientEncryptionKeyGetResults"]: - """Lists the ClientEncryptionKeys under an existing Azure Cosmos DB SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: An iterator like instance of either ClientEncryptionKeyGetResults or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.ClientEncryptionKeyGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ClientEncryptionKeysListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_client_encryption_keys_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("ClientEncryptionKeysListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get_client_encryption_key( - self, - resource_group_name: str, - account_name: str, - database_name: str, - client_encryption_key_name: str, - **kwargs: Any - ) -> _models.ClientEncryptionKeyGetResults: - """Gets the ClientEncryptionKey under an existing Azure Cosmos DB SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param client_encryption_key_name: Cosmos DB ClientEncryptionKey name. Required. - :type client_encryption_key_name: str - :return: ClientEncryptionKeyGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ClientEncryptionKeyGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ClientEncryptionKeyGetResults] = kwargs.pop("cls", None) - - _request = build_get_client_encryption_key_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - client_encryption_key_name=client_encryption_key_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ClientEncryptionKeyGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _create_update_client_encryption_key_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - client_encryption_key_name: str, - create_update_client_encryption_key_parameters: Union[ - _models.ClientEncryptionKeyCreateUpdateParameters, IO[bytes] - ], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_client_encryption_key_parameters, (IOBase, bytes)): - _content = create_update_client_encryption_key_parameters - else: - _json = self._serialize.body( - create_update_client_encryption_key_parameters, "ClientEncryptionKeyCreateUpdateParameters" - ) - - _request = build_create_update_client_encryption_key_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - client_encryption_key_name=client_encryption_key_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_update_client_encryption_key( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - client_encryption_key_name: str, - create_update_client_encryption_key_parameters: _models.ClientEncryptionKeyCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ClientEncryptionKeyGetResults]: - """Create or update a ClientEncryptionKey. This API is meant to be invoked via tools such as the - Azure Powershell (instead of directly). - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param client_encryption_key_name: Cosmos DB ClientEncryptionKey name. Required. - :type client_encryption_key_name: str - :param create_update_client_encryption_key_parameters: The parameters to provide for the client - encryption key. Required. - :type create_update_client_encryption_key_parameters: - ~azure.mgmt.cosmosdb.models.ClientEncryptionKeyCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ClientEncryptionKeyGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ClientEncryptionKeyGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_update_client_encryption_key( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - client_encryption_key_name: str, - create_update_client_encryption_key_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ClientEncryptionKeyGetResults]: - """Create or update a ClientEncryptionKey. This API is meant to be invoked via tools such as the - Azure Powershell (instead of directly). - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param client_encryption_key_name: Cosmos DB ClientEncryptionKey name. Required. - :type client_encryption_key_name: str - :param create_update_client_encryption_key_parameters: The parameters to provide for the client - encryption key. Required. - :type create_update_client_encryption_key_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ClientEncryptionKeyGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ClientEncryptionKeyGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_update_client_encryption_key( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - client_encryption_key_name: str, - create_update_client_encryption_key_parameters: Union[ - _models.ClientEncryptionKeyCreateUpdateParameters, IO[bytes] - ], - **kwargs: Any - ) -> AsyncLROPoller[_models.ClientEncryptionKeyGetResults]: - """Create or update a ClientEncryptionKey. This API is meant to be invoked via tools such as the - Azure Powershell (instead of directly). - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param client_encryption_key_name: Cosmos DB ClientEncryptionKey name. Required. - :type client_encryption_key_name: str - :param create_update_client_encryption_key_parameters: The parameters to provide for the client - encryption key. Is either a ClientEncryptionKeyCreateUpdateParameters type or a IO[bytes] type. - Required. - :type create_update_client_encryption_key_parameters: - ~azure.mgmt.cosmosdb.models.ClientEncryptionKeyCreateUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either ClientEncryptionKeyGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ClientEncryptionKeyGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ClientEncryptionKeyGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_update_client_encryption_key_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - client_encryption_key_name=client_encryption_key_name, - create_update_client_encryption_key_parameters=create_update_client_encryption_key_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ClientEncryptionKeyGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ClientEncryptionKeyGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ClientEncryptionKeyGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @distributed_trace - def list_sql_containers( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> AsyncIterable["_models.SqlContainerGetResults"]: - """Lists the SQL container under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: An iterator like instance of either SqlContainerGetResults or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.SqlContainerGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SqlContainerListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_sql_containers_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("SqlContainerListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get_sql_container( - self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any - ) -> _models.SqlContainerGetResults: - """Gets the SQL container under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :return: SqlContainerGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.SqlContainerGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SqlContainerGetResults] = kwargs.pop("cls", None) - - _request = build_get_sql_container_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("SqlContainerGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _create_update_sql_container_initial( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - create_update_sql_container_parameters: Union[_models.SqlContainerCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_sql_container_parameters, (IOBase, bytes)): - _content = create_update_sql_container_parameters - else: - _json = self._serialize.body(create_update_sql_container_parameters, "SqlContainerCreateUpdateParameters") - - _request = build_create_update_sql_container_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_update_sql_container( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - create_update_sql_container_parameters: _models.SqlContainerCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.SqlContainerGetResults]: - """Create or update an Azure Cosmos DB SQL container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param create_update_sql_container_parameters: The parameters to provide for the current SQL - container. Required. - :type create_update_sql_container_parameters: - ~azure.mgmt.cosmosdb.models.SqlContainerCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either SqlContainerGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlContainerGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_update_sql_container( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - create_update_sql_container_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.SqlContainerGetResults]: - """Create or update an Azure Cosmos DB SQL container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param create_update_sql_container_parameters: The parameters to provide for the current SQL - container. Required. - :type create_update_sql_container_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either SqlContainerGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlContainerGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_update_sql_container( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - create_update_sql_container_parameters: Union[_models.SqlContainerCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.SqlContainerGetResults]: - """Create or update an Azure Cosmos DB SQL container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param create_update_sql_container_parameters: The parameters to provide for the current SQL - container. Is either a SqlContainerCreateUpdateParameters type or a IO[bytes] type. Required. - :type create_update_sql_container_parameters: - ~azure.mgmt.cosmosdb.models.SqlContainerCreateUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either SqlContainerGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlContainerGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SqlContainerGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_update_sql_container_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - create_update_sql_container_parameters=create_update_sql_container_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("SqlContainerGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.SqlContainerGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.SqlContainerGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _delete_sql_container_initial( - self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_sql_container_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete_sql_container( - self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes an existing Azure Cosmos DB SQL container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_sql_container_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - async def _sql_database_partition_merge_initial( - self, - resource_group_name: str, - account_name: str, - database_name: str, - merge_parameters: Union[_models.MergeParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(merge_parameters, (IOBase, bytes)): - _content = merge_parameters - else: - _json = self._serialize.body(merge_parameters, "MergeParameters") - - _request = build_sql_database_partition_merge_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_sql_database_partition_merge( - self, - resource_group_name: str, - account_name: str, - database_name: str, - merge_parameters: _models.MergeParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]: - """Merges the partitions of a SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param merge_parameters: The parameters for the merge operation. Required. - :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionStorageInfoCollection or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_sql_database_partition_merge( - self, - resource_group_name: str, - account_name: str, - database_name: str, - merge_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]: - """Merges the partitions of a SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param merge_parameters: The parameters for the merge operation. Required. - :type merge_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionStorageInfoCollection or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_sql_database_partition_merge( - self, - resource_group_name: str, - account_name: str, - database_name: str, - merge_parameters: Union[_models.MergeParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]: - """Merges the partitions of a SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param merge_parameters: The parameters for the merge operation. Is either a MergeParameters - type or a IO[bytes] type. Required. - :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionStorageInfoCollection or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PhysicalPartitionStorageInfoCollection] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._sql_database_partition_merge_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - merge_parameters=merge_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("PhysicalPartitionStorageInfoCollection", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _list_sql_container_partition_merge_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - merge_parameters: Union[_models.MergeParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(merge_parameters, (IOBase, bytes)): - _content = merge_parameters - else: - _json = self._serialize.body(merge_parameters, "MergeParameters") - - _request = build_list_sql_container_partition_merge_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_list_sql_container_partition_merge( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - merge_parameters: _models.MergeParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]: - """Merges the partitions of a SQL Container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param merge_parameters: The parameters for the merge operation. Required. - :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionStorageInfoCollection or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_list_sql_container_partition_merge( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - merge_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]: - """Merges the partitions of a SQL Container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param merge_parameters: The parameters for the merge operation. Required. - :type merge_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionStorageInfoCollection or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_list_sql_container_partition_merge( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - merge_parameters: Union[_models.MergeParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]: - """Merges the partitions of a SQL Container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param merge_parameters: The parameters for the merge operation. Is either a MergeParameters - type or a IO[bytes] type. Required. - :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionStorageInfoCollection or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PhysicalPartitionStorageInfoCollection] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._list_sql_container_partition_merge_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - merge_parameters=merge_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("PhysicalPartitionStorageInfoCollection", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @distributed_trace_async - async def get_sql_container_throughput( - self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any - ) -> _models.ThroughputSettingsGetResults: - """Gets the RUs per second of the SQL container under an existing Azure Cosmos DB database - account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :return: ThroughputSettingsGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - - _request = build_get_sql_container_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _update_sql_container_throughput_initial( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(update_throughput_parameters, (IOBase, bytes)): - _content = update_throughput_parameters - else: - _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") - - _request = build_update_sql_container_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_update_sql_container_throughput( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB SQL container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param update_throughput_parameters: The parameters to provide for the RUs per second of the - current SQL container. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_update_sql_container_throughput( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - update_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB SQL container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param update_throughput_parameters: The parameters to provide for the RUs per second of the - current SQL container. Required. - :type update_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_update_sql_container_throughput( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB SQL container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param update_throughput_parameters: The parameters to provide for the RUs per second of the - current SQL container. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] type. - Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._update_sql_container_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - update_throughput_parameters=update_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _migrate_sql_container_to_autoscale_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_sql_container_to_autoscale_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_migrate_sql_container_to_autoscale( - self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB SQL container from manual throughput to autoscale. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._migrate_sql_container_to_autoscale_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _migrate_sql_container_to_manual_throughput_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_sql_container_to_manual_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_migrate_sql_container_to_manual_throughput( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB SQL container from autoscale to manual throughput. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._migrate_sql_container_to_manual_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _sql_database_retrieve_throughput_distribution_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(retrieve_throughput_parameters, (IOBase, bytes)): - _content = retrieve_throughput_parameters - else: - _json = self._serialize.body(retrieve_throughput_parameters, "RetrieveThroughputParameters") - - _request = build_sql_database_retrieve_throughput_distribution_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_sql_database_retrieve_throughput_distribution( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - retrieve_throughput_parameters: _models.RetrieveThroughputParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Retrieve throughput distribution for an Azure Cosmos DB SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput - distribution for the current SQL database. Required. - :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionThroughputInfoResult or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_sql_database_retrieve_throughput_distribution( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - retrieve_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Retrieve throughput distribution for an Azure Cosmos DB SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput - distribution for the current SQL database. Required. - :type retrieve_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionThroughputInfoResult or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_sql_database_retrieve_throughput_distribution( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Retrieve throughput distribution for an Azure Cosmos DB SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput - distribution for the current SQL database. Is either a RetrieveThroughputParameters type or a - IO[bytes] type. Required. - :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters - or IO[bytes] - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionThroughputInfoResult or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._sql_database_retrieve_throughput_distribution_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - retrieve_throughput_parameters=retrieve_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _sql_database_redistribute_throughput_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(redistribute_throughput_parameters, (IOBase, bytes)): - _content = redistribute_throughput_parameters - else: - _json = self._serialize.body(redistribute_throughput_parameters, "RedistributeThroughputParameters") - - _request = build_sql_database_redistribute_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_sql_database_redistribute_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - redistribute_throughput_parameters: _models.RedistributeThroughputParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Redistribute throughput for an Azure Cosmos DB SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param redistribute_throughput_parameters: The parameters to provide for redistributing - throughput for the current SQL database. Required. - :type redistribute_throughput_parameters: - ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionThroughputInfoResult or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_sql_database_redistribute_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - redistribute_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Redistribute throughput for an Azure Cosmos DB SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param redistribute_throughput_parameters: The parameters to provide for redistributing - throughput for the current SQL database. Required. - :type redistribute_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionThroughputInfoResult or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_sql_database_redistribute_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Redistribute throughput for an Azure Cosmos DB SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param redistribute_throughput_parameters: The parameters to provide for redistributing - throughput for the current SQL database. Is either a RedistributeThroughputParameters type or a - IO[bytes] type. Required. - :type redistribute_throughput_parameters: - ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionThroughputInfoResult or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._sql_database_redistribute_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - redistribute_throughput_parameters=redistribute_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _sql_container_retrieve_throughput_distribution_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(retrieve_throughput_parameters, (IOBase, bytes)): - _content = retrieve_throughput_parameters - else: - _json = self._serialize.body(retrieve_throughput_parameters, "RetrieveThroughputParameters") - - _request = build_sql_container_retrieve_throughput_distribution_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_sql_container_retrieve_throughput_distribution( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - retrieve_throughput_parameters: _models.RetrieveThroughputParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Retrieve throughput distribution for an Azure Cosmos DB SQL container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput - distribution for the current SQL container. Required. - :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionThroughputInfoResult or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_sql_container_retrieve_throughput_distribution( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - retrieve_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Retrieve throughput distribution for an Azure Cosmos DB SQL container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput - distribution for the current SQL container. Required. - :type retrieve_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionThroughputInfoResult or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_sql_container_retrieve_throughput_distribution( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Retrieve throughput distribution for an Azure Cosmos DB SQL container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput - distribution for the current SQL container. Is either a RetrieveThroughputParameters type or a - IO[bytes] type. Required. - :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters - or IO[bytes] - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionThroughputInfoResult or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._sql_container_retrieve_throughput_distribution_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - retrieve_throughput_parameters=retrieve_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _sql_container_redistribute_throughput_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(redistribute_throughput_parameters, (IOBase, bytes)): - _content = redistribute_throughput_parameters - else: - _json = self._serialize.body(redistribute_throughput_parameters, "RedistributeThroughputParameters") - - _request = build_sql_container_redistribute_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_sql_container_redistribute_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - redistribute_throughput_parameters: _models.RedistributeThroughputParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Redistribute throughput for an Azure Cosmos DB SQL container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param redistribute_throughput_parameters: The parameters to provide for redistributing - throughput for the current SQL container. Required. - :type redistribute_throughput_parameters: - ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionThroughputInfoResult or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_sql_container_redistribute_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - redistribute_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Redistribute throughput for an Azure Cosmos DB SQL container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param redistribute_throughput_parameters: The parameters to provide for redistributing - throughput for the current SQL container. Required. - :type redistribute_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionThroughputInfoResult or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_sql_container_redistribute_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Redistribute throughput for an Azure Cosmos DB SQL container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param redistribute_throughput_parameters: The parameters to provide for redistributing - throughput for the current SQL container. Is either a RedistributeThroughputParameters type or - a IO[bytes] type. Required. - :type redistribute_throughput_parameters: - ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either - PhysicalPartitionThroughputInfoResult or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._sql_container_redistribute_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - redistribute_throughput_parameters=redistribute_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @distributed_trace - def list_sql_stored_procedures( - self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any - ) -> AsyncIterable["_models.SqlStoredProcedureGetResults"]: - """Lists the SQL storedProcedure under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :return: An iterator like instance of either SqlStoredProcedureGetResults or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.SqlStoredProcedureGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SqlStoredProcedureListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_sql_stored_procedures_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("SqlStoredProcedureListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get_sql_stored_procedure( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - stored_procedure_name: str, - **kwargs: Any - ) -> _models.SqlStoredProcedureGetResults: - """Gets the SQL storedProcedure under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param stored_procedure_name: Cosmos DB storedProcedure name. Required. - :type stored_procedure_name: str - :return: SqlStoredProcedureGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.SqlStoredProcedureGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SqlStoredProcedureGetResults] = kwargs.pop("cls", None) - - _request = build_get_sql_stored_procedure_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - stored_procedure_name=stored_procedure_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("SqlStoredProcedureGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _create_update_sql_stored_procedure_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - stored_procedure_name: str, - create_update_sql_stored_procedure_parameters: Union[ - _models.SqlStoredProcedureCreateUpdateParameters, IO[bytes] - ], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_sql_stored_procedure_parameters, (IOBase, bytes)): - _content = create_update_sql_stored_procedure_parameters - else: - _json = self._serialize.body( - create_update_sql_stored_procedure_parameters, "SqlStoredProcedureCreateUpdateParameters" - ) - - _request = build_create_update_sql_stored_procedure_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - stored_procedure_name=stored_procedure_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_update_sql_stored_procedure( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - stored_procedure_name: str, - create_update_sql_stored_procedure_parameters: _models.SqlStoredProcedureCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.SqlStoredProcedureGetResults]: - """Create or update an Azure Cosmos DB SQL storedProcedure. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param stored_procedure_name: Cosmos DB storedProcedure name. Required. - :type stored_procedure_name: str - :param create_update_sql_stored_procedure_parameters: The parameters to provide for the current - SQL storedProcedure. Required. - :type create_update_sql_stored_procedure_parameters: - ~azure.mgmt.cosmosdb.models.SqlStoredProcedureCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either SqlStoredProcedureGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlStoredProcedureGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_update_sql_stored_procedure( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - stored_procedure_name: str, - create_update_sql_stored_procedure_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.SqlStoredProcedureGetResults]: - """Create or update an Azure Cosmos DB SQL storedProcedure. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param stored_procedure_name: Cosmos DB storedProcedure name. Required. - :type stored_procedure_name: str - :param create_update_sql_stored_procedure_parameters: The parameters to provide for the current - SQL storedProcedure. Required. - :type create_update_sql_stored_procedure_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either SqlStoredProcedureGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlStoredProcedureGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_update_sql_stored_procedure( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - stored_procedure_name: str, - create_update_sql_stored_procedure_parameters: Union[ - _models.SqlStoredProcedureCreateUpdateParameters, IO[bytes] - ], - **kwargs: Any - ) -> AsyncLROPoller[_models.SqlStoredProcedureGetResults]: - """Create or update an Azure Cosmos DB SQL storedProcedure. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param stored_procedure_name: Cosmos DB storedProcedure name. Required. - :type stored_procedure_name: str - :param create_update_sql_stored_procedure_parameters: The parameters to provide for the current - SQL storedProcedure. Is either a SqlStoredProcedureCreateUpdateParameters type or a IO[bytes] - type. Required. - :type create_update_sql_stored_procedure_parameters: - ~azure.mgmt.cosmosdb.models.SqlStoredProcedureCreateUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either SqlStoredProcedureGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlStoredProcedureGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SqlStoredProcedureGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_update_sql_stored_procedure_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - stored_procedure_name=stored_procedure_name, - create_update_sql_stored_procedure_parameters=create_update_sql_stored_procedure_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("SqlStoredProcedureGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.SqlStoredProcedureGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.SqlStoredProcedureGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _delete_sql_stored_procedure_initial( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - stored_procedure_name: str, - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_sql_stored_procedure_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - stored_procedure_name=stored_procedure_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete_sql_stored_procedure( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - stored_procedure_name: str, - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes an existing Azure Cosmos DB SQL storedProcedure. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param stored_procedure_name: Cosmos DB storedProcedure name. Required. - :type stored_procedure_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_sql_stored_procedure_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - stored_procedure_name=stored_procedure_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace - def list_sql_user_defined_functions( - self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any - ) -> AsyncIterable["_models.SqlUserDefinedFunctionGetResults"]: - """Lists the SQL userDefinedFunction under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :return: An iterator like instance of either SqlUserDefinedFunctionGetResults or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SqlUserDefinedFunctionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_sql_user_defined_functions_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("SqlUserDefinedFunctionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get_sql_user_defined_function( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - user_defined_function_name: str, - **kwargs: Any - ) -> _models.SqlUserDefinedFunctionGetResults: - """Gets the SQL userDefinedFunction under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param user_defined_function_name: Cosmos DB userDefinedFunction name. Required. - :type user_defined_function_name: str - :return: SqlUserDefinedFunctionGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SqlUserDefinedFunctionGetResults] = kwargs.pop("cls", None) - - _request = build_get_sql_user_defined_function_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - user_defined_function_name=user_defined_function_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("SqlUserDefinedFunctionGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _create_update_sql_user_defined_function_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - user_defined_function_name: str, - create_update_sql_user_defined_function_parameters: Union[ - _models.SqlUserDefinedFunctionCreateUpdateParameters, IO[bytes] - ], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_sql_user_defined_function_parameters, (IOBase, bytes)): - _content = create_update_sql_user_defined_function_parameters - else: - _json = self._serialize.body( - create_update_sql_user_defined_function_parameters, "SqlUserDefinedFunctionCreateUpdateParameters" - ) - - _request = build_create_update_sql_user_defined_function_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - user_defined_function_name=user_defined_function_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_update_sql_user_defined_function( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - user_defined_function_name: str, - create_update_sql_user_defined_function_parameters: _models.SqlUserDefinedFunctionCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.SqlUserDefinedFunctionGetResults]: - """Create or update an Azure Cosmos DB SQL userDefinedFunction. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param user_defined_function_name: Cosmos DB userDefinedFunction name. Required. - :type user_defined_function_name: str - :param create_update_sql_user_defined_function_parameters: The parameters to provide for the - current SQL userDefinedFunction. Required. - :type create_update_sql_user_defined_function_parameters: - ~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either SqlUserDefinedFunctionGetResults or - the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_update_sql_user_defined_function( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - user_defined_function_name: str, - create_update_sql_user_defined_function_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.SqlUserDefinedFunctionGetResults]: - """Create or update an Azure Cosmos DB SQL userDefinedFunction. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param user_defined_function_name: Cosmos DB userDefinedFunction name. Required. - :type user_defined_function_name: str - :param create_update_sql_user_defined_function_parameters: The parameters to provide for the - current SQL userDefinedFunction. Required. - :type create_update_sql_user_defined_function_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either SqlUserDefinedFunctionGetResults or - the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_update_sql_user_defined_function( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - user_defined_function_name: str, - create_update_sql_user_defined_function_parameters: Union[ - _models.SqlUserDefinedFunctionCreateUpdateParameters, IO[bytes] - ], - **kwargs: Any - ) -> AsyncLROPoller[_models.SqlUserDefinedFunctionGetResults]: - """Create or update an Azure Cosmos DB SQL userDefinedFunction. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param user_defined_function_name: Cosmos DB userDefinedFunction name. Required. - :type user_defined_function_name: str - :param create_update_sql_user_defined_function_parameters: The parameters to provide for the - current SQL userDefinedFunction. Is either a SqlUserDefinedFunctionCreateUpdateParameters type - or a IO[bytes] type. Required. - :type create_update_sql_user_defined_function_parameters: - ~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionCreateUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either SqlUserDefinedFunctionGetResults or - the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SqlUserDefinedFunctionGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_update_sql_user_defined_function_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - user_defined_function_name=user_defined_function_name, - create_update_sql_user_defined_function_parameters=create_update_sql_user_defined_function_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("SqlUserDefinedFunctionGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.SqlUserDefinedFunctionGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.SqlUserDefinedFunctionGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _delete_sql_user_defined_function_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - user_defined_function_name: str, - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_sql_user_defined_function_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - user_defined_function_name=user_defined_function_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete_sql_user_defined_function( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - user_defined_function_name: str, - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes an existing Azure Cosmos DB SQL userDefinedFunction. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param user_defined_function_name: Cosmos DB userDefinedFunction name. Required. - :type user_defined_function_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_sql_user_defined_function_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - user_defined_function_name=user_defined_function_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace - def list_sql_triggers( - self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any - ) -> AsyncIterable["_models.SqlTriggerGetResults"]: - """Lists the SQL trigger under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :return: An iterator like instance of either SqlTriggerGetResults or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.SqlTriggerGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SqlTriggerListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_sql_triggers_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("SqlTriggerListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get_sql_trigger( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - trigger_name: str, - **kwargs: Any - ) -> _models.SqlTriggerGetResults: - """Gets the SQL trigger under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param trigger_name: Cosmos DB trigger name. Required. - :type trigger_name: str - :return: SqlTriggerGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.SqlTriggerGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SqlTriggerGetResults] = kwargs.pop("cls", None) - - _request = build_get_sql_trigger_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - trigger_name=trigger_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("SqlTriggerGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _create_update_sql_trigger_initial( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - trigger_name: str, - create_update_sql_trigger_parameters: Union[_models.SqlTriggerCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_sql_trigger_parameters, (IOBase, bytes)): - _content = create_update_sql_trigger_parameters - else: - _json = self._serialize.body(create_update_sql_trigger_parameters, "SqlTriggerCreateUpdateParameters") - - _request = build_create_update_sql_trigger_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - trigger_name=trigger_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_update_sql_trigger( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - trigger_name: str, - create_update_sql_trigger_parameters: _models.SqlTriggerCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.SqlTriggerGetResults]: - """Create or update an Azure Cosmos DB SQL trigger. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param trigger_name: Cosmos DB trigger name. Required. - :type trigger_name: str - :param create_update_sql_trigger_parameters: The parameters to provide for the current SQL - trigger. Required. - :type create_update_sql_trigger_parameters: - ~azure.mgmt.cosmosdb.models.SqlTriggerCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either SqlTriggerGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlTriggerGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_update_sql_trigger( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - trigger_name: str, - create_update_sql_trigger_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.SqlTriggerGetResults]: - """Create or update an Azure Cosmos DB SQL trigger. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param trigger_name: Cosmos DB trigger name. Required. - :type trigger_name: str - :param create_update_sql_trigger_parameters: The parameters to provide for the current SQL - trigger. Required. - :type create_update_sql_trigger_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either SqlTriggerGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlTriggerGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_update_sql_trigger( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - trigger_name: str, - create_update_sql_trigger_parameters: Union[_models.SqlTriggerCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.SqlTriggerGetResults]: - """Create or update an Azure Cosmos DB SQL trigger. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param trigger_name: Cosmos DB trigger name. Required. - :type trigger_name: str - :param create_update_sql_trigger_parameters: The parameters to provide for the current SQL - trigger. Is either a SqlTriggerCreateUpdateParameters type or a IO[bytes] type. Required. - :type create_update_sql_trigger_parameters: - ~azure.mgmt.cosmosdb.models.SqlTriggerCreateUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either SqlTriggerGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlTriggerGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SqlTriggerGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_update_sql_trigger_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - trigger_name=trigger_name, - create_update_sql_trigger_parameters=create_update_sql_trigger_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("SqlTriggerGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.SqlTriggerGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.SqlTriggerGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _delete_sql_trigger_initial( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - trigger_name: str, - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_sql_trigger_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - trigger_name=trigger_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete_sql_trigger( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - trigger_name: str, - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes an existing Azure Cosmos DB SQL trigger. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param trigger_name: Cosmos DB trigger name. Required. - :type trigger_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_sql_trigger_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - trigger_name=trigger_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace_async - async def get_sql_role_definition( - self, role_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any - ) -> _models.SqlRoleDefinitionGetResults: - """Retrieves the properties of an existing Azure Cosmos DB SQL Role Definition with the given Id. - - :param role_definition_id: The GUID for the Role Definition. Required. - :type role_definition_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: SqlRoleDefinitionGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.SqlRoleDefinitionGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SqlRoleDefinitionGetResults] = kwargs.pop("cls", None) - - _request = build_get_sql_role_definition_request( - role_definition_id=role_definition_id, - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("SqlRoleDefinitionGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _create_update_sql_role_definition_initial( # pylint: disable=name-too-long - self, - role_definition_id: str, - resource_group_name: str, - account_name: str, - create_update_sql_role_definition_parameters: Union[_models.SqlRoleDefinitionCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_sql_role_definition_parameters, (IOBase, bytes)): - _content = create_update_sql_role_definition_parameters - else: - _json = self._serialize.body( - create_update_sql_role_definition_parameters, "SqlRoleDefinitionCreateUpdateParameters" - ) - - _request = build_create_update_sql_role_definition_request( - role_definition_id=role_definition_id, - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_update_sql_role_definition( - self, - role_definition_id: str, - resource_group_name: str, - account_name: str, - create_update_sql_role_definition_parameters: _models.SqlRoleDefinitionCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.SqlRoleDefinitionGetResults]: - """Creates or updates an Azure Cosmos DB SQL Role Definition. - - :param role_definition_id: The GUID for the Role Definition. Required. - :type role_definition_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param create_update_sql_role_definition_parameters: The properties required to create or - update a Role Definition. Required. - :type create_update_sql_role_definition_parameters: - ~azure.mgmt.cosmosdb.models.SqlRoleDefinitionCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either SqlRoleDefinitionGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlRoleDefinitionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_update_sql_role_definition( - self, - role_definition_id: str, - resource_group_name: str, - account_name: str, - create_update_sql_role_definition_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.SqlRoleDefinitionGetResults]: - """Creates or updates an Azure Cosmos DB SQL Role Definition. - - :param role_definition_id: The GUID for the Role Definition. Required. - :type role_definition_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param create_update_sql_role_definition_parameters: The properties required to create or - update a Role Definition. Required. - :type create_update_sql_role_definition_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either SqlRoleDefinitionGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlRoleDefinitionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_update_sql_role_definition( - self, - role_definition_id: str, - resource_group_name: str, - account_name: str, - create_update_sql_role_definition_parameters: Union[_models.SqlRoleDefinitionCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.SqlRoleDefinitionGetResults]: - """Creates or updates an Azure Cosmos DB SQL Role Definition. - - :param role_definition_id: The GUID for the Role Definition. Required. - :type role_definition_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param create_update_sql_role_definition_parameters: The properties required to create or - update a Role Definition. Is either a SqlRoleDefinitionCreateUpdateParameters type or a - IO[bytes] type. Required. - :type create_update_sql_role_definition_parameters: - ~azure.mgmt.cosmosdb.models.SqlRoleDefinitionCreateUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either SqlRoleDefinitionGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlRoleDefinitionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SqlRoleDefinitionGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_update_sql_role_definition_initial( - role_definition_id=role_definition_id, - resource_group_name=resource_group_name, - account_name=account_name, - create_update_sql_role_definition_parameters=create_update_sql_role_definition_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("SqlRoleDefinitionGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.SqlRoleDefinitionGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.SqlRoleDefinitionGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _delete_sql_role_definition_initial( - self, role_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_sql_role_definition_request( - role_definition_id=role_definition_id, - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202, 204]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete_sql_role_definition( - self, role_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes an existing Azure Cosmos DB SQL Role Definition. - - :param role_definition_id: The GUID for the Role Definition. Required. - :type role_definition_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_sql_role_definition_initial( - role_definition_id=role_definition_id, - resource_group_name=resource_group_name, - account_name=account_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace - def list_sql_role_definitions( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> AsyncIterable["_models.SqlRoleDefinitionGetResults"]: - """Retrieves the list of all Azure Cosmos DB SQL Role Definitions. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either SqlRoleDefinitionGetResults or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.SqlRoleDefinitionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SqlRoleDefinitionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_sql_role_definitions_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("SqlRoleDefinitionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get_sql_role_assignment( - self, role_assignment_id: str, resource_group_name: str, account_name: str, **kwargs: Any - ) -> _models.SqlRoleAssignmentGetResults: - """Retrieves the properties of an existing Azure Cosmos DB SQL Role Assignment with the given Id. - - :param role_assignment_id: The GUID for the Role Assignment. Required. - :type role_assignment_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: SqlRoleAssignmentGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.SqlRoleAssignmentGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SqlRoleAssignmentGetResults] = kwargs.pop("cls", None) - - _request = build_get_sql_role_assignment_request( - role_assignment_id=role_assignment_id, - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("SqlRoleAssignmentGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _create_update_sql_role_assignment_initial( # pylint: disable=name-too-long - self, - role_assignment_id: str, - resource_group_name: str, - account_name: str, - create_update_sql_role_assignment_parameters: Union[_models.SqlRoleAssignmentCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_sql_role_assignment_parameters, (IOBase, bytes)): - _content = create_update_sql_role_assignment_parameters - else: - _json = self._serialize.body( - create_update_sql_role_assignment_parameters, "SqlRoleAssignmentCreateUpdateParameters" - ) - - _request = build_create_update_sql_role_assignment_request( - role_assignment_id=role_assignment_id, - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_update_sql_role_assignment( - self, - role_assignment_id: str, - resource_group_name: str, - account_name: str, - create_update_sql_role_assignment_parameters: _models.SqlRoleAssignmentCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.SqlRoleAssignmentGetResults]: - """Creates or updates an Azure Cosmos DB SQL Role Assignment. - - :param role_assignment_id: The GUID for the Role Assignment. Required. - :type role_assignment_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param create_update_sql_role_assignment_parameters: The properties required to create or - update a Role Assignment. Required. - :type create_update_sql_role_assignment_parameters: - ~azure.mgmt.cosmosdb.models.SqlRoleAssignmentCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either SqlRoleAssignmentGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlRoleAssignmentGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_update_sql_role_assignment( - self, - role_assignment_id: str, - resource_group_name: str, - account_name: str, - create_update_sql_role_assignment_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.SqlRoleAssignmentGetResults]: - """Creates or updates an Azure Cosmos DB SQL Role Assignment. - - :param role_assignment_id: The GUID for the Role Assignment. Required. - :type role_assignment_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param create_update_sql_role_assignment_parameters: The properties required to create or - update a Role Assignment. Required. - :type create_update_sql_role_assignment_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either SqlRoleAssignmentGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlRoleAssignmentGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_update_sql_role_assignment( - self, - role_assignment_id: str, - resource_group_name: str, - account_name: str, - create_update_sql_role_assignment_parameters: Union[_models.SqlRoleAssignmentCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.SqlRoleAssignmentGetResults]: - """Creates or updates an Azure Cosmos DB SQL Role Assignment. - - :param role_assignment_id: The GUID for the Role Assignment. Required. - :type role_assignment_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param create_update_sql_role_assignment_parameters: The properties required to create or - update a Role Assignment. Is either a SqlRoleAssignmentCreateUpdateParameters type or a - IO[bytes] type. Required. - :type create_update_sql_role_assignment_parameters: - ~azure.mgmt.cosmosdb.models.SqlRoleAssignmentCreateUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either SqlRoleAssignmentGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlRoleAssignmentGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SqlRoleAssignmentGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_update_sql_role_assignment_initial( - role_assignment_id=role_assignment_id, - resource_group_name=resource_group_name, - account_name=account_name, - create_update_sql_role_assignment_parameters=create_update_sql_role_assignment_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("SqlRoleAssignmentGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.SqlRoleAssignmentGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.SqlRoleAssignmentGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _delete_sql_role_assignment_initial( - self, role_assignment_id: str, resource_group_name: str, account_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_sql_role_assignment_request( - role_assignment_id=role_assignment_id, - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202, 204]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete_sql_role_assignment( - self, role_assignment_id: str, resource_group_name: str, account_name: str, **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes an existing Azure Cosmos DB SQL Role Assignment. - - :param role_assignment_id: The GUID for the Role Assignment. Required. - :type role_assignment_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_sql_role_assignment_initial( - role_assignment_id=role_assignment_id, - resource_group_name=resource_group_name, - account_name=account_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace - def list_sql_role_assignments( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> AsyncIterable["_models.SqlRoleAssignmentGetResults"]: - """Retrieves the list of all Azure Cosmos DB SQL Role Assignments. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either SqlRoleAssignmentGetResults or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.SqlRoleAssignmentGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SqlRoleAssignmentListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_sql_role_assignments_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("SqlRoleAssignmentListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - async def _retrieve_continuous_backup_information_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(location, (IOBase, bytes)): - _content = location - else: - _json = self._serialize.body(location, "ContinuousBackupRestoreLocation") - - _request = build_retrieve_continuous_backup_information_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - location: _models.ContinuousBackupRestoreLocation, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.BackupInformation]: - """Retrieves continuous backup information for a container resource. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param location: The name of the continuous backup restore location. Required. - :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either BackupInformation or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - location: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.BackupInformation]: - """Retrieves continuous backup information for a container resource. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param location: The name of the continuous backup restore location. Required. - :type location: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either BackupInformation or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.BackupInformation]: - """Retrieves continuous backup information for a container resource. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param location: The name of the continuous backup restore location. Is either a - ContinuousBackupRestoreLocation type or a IO[bytes] type. Required. - :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation or IO[bytes] - :return: An instance of AsyncLROPoller that returns either BackupInformation or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.BackupInformation] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._retrieve_continuous_backup_information_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - location=location, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("BackupInformation", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.BackupInformation].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.BackupInformation]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ...operations._sql_resources_operations import ( + build_create_update_client_encryption_key_request, + build_create_update_sql_container_request, + build_create_update_sql_database_request, + build_create_update_sql_role_assignment_request, + build_create_update_sql_role_definition_request, + build_create_update_sql_stored_procedure_request, + build_create_update_sql_trigger_request, + build_create_update_sql_user_defined_function_request, + build_delete_sql_container_request, + build_delete_sql_database_request, + build_delete_sql_role_assignment_request, + build_delete_sql_role_definition_request, + build_delete_sql_stored_procedure_request, + build_delete_sql_trigger_request, + build_delete_sql_user_defined_function_request, + build_get_client_encryption_key_request, + build_get_sql_container_request, + build_get_sql_container_throughput_request, + build_get_sql_database_request, + build_get_sql_database_throughput_request, + build_get_sql_role_assignment_request, + build_get_sql_role_definition_request, + build_get_sql_stored_procedure_request, + build_get_sql_trigger_request, + build_get_sql_user_defined_function_request, + build_list_client_encryption_keys_request, + build_list_sql_container_partition_merge_request, + build_list_sql_containers_request, + build_list_sql_databases_request, + build_list_sql_role_assignments_request, + build_list_sql_role_definitions_request, + build_list_sql_stored_procedures_request, + build_list_sql_triggers_request, + build_list_sql_user_defined_functions_request, + build_migrate_sql_container_to_autoscale_request, + build_migrate_sql_container_to_manual_throughput_request, + build_migrate_sql_database_to_autoscale_request, + build_migrate_sql_database_to_manual_throughput_request, + build_retrieve_continuous_backup_information_request, + build_sql_container_redistribute_throughput_request, + build_sql_container_retrieve_throughput_distribution_request, + build_sql_database_partition_merge_request, + build_sql_database_redistribute_throughput_request, + build_sql_database_retrieve_throughput_distribution_request, + build_update_sql_container_throughput_request, + build_update_sql_database_throughput_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class SqlResourcesOperations: # pylint: disable=too-many-public-methods + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`sql_resources` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_sql_databases( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> AsyncIterable["_models.SqlDatabaseGetResults"]: + """Lists the SQL databases under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either SqlDatabaseGetResults or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.SqlDatabaseGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SqlDatabaseListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_sql_databases_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("SqlDatabaseListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get_sql_database( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> _models.SqlDatabaseGetResults: + """Gets the SQL database under an existing Azure Cosmos DB database account with the provided + name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: SqlDatabaseGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.SqlDatabaseGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SqlDatabaseGetResults] = kwargs.pop("cls", None) + + _request = build_get_sql_database_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("SqlDatabaseGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_update_sql_database_initial( + self, + resource_group_name: str, + account_name: str, + database_name: str, + create_update_sql_database_parameters: Union[_models.SqlDatabaseCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_sql_database_parameters, (IOBase, bytes)): + _content = create_update_sql_database_parameters + else: + _json = self._serialize.body(create_update_sql_database_parameters, "SqlDatabaseCreateUpdateParameters") + + _request = build_create_update_sql_database_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_update_sql_database( + self, + resource_group_name: str, + account_name: str, + database_name: str, + create_update_sql_database_parameters: _models.SqlDatabaseCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.SqlDatabaseGetResults]: + """Create or update an Azure Cosmos DB SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param create_update_sql_database_parameters: The parameters to provide for the current SQL + database. Required. + :type create_update_sql_database_parameters: + ~azure.mgmt.cosmosdb.models.SqlDatabaseCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either SqlDatabaseGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlDatabaseGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_update_sql_database( + self, + resource_group_name: str, + account_name: str, + database_name: str, + create_update_sql_database_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.SqlDatabaseGetResults]: + """Create or update an Azure Cosmos DB SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param create_update_sql_database_parameters: The parameters to provide for the current SQL + database. Required. + :type create_update_sql_database_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either SqlDatabaseGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlDatabaseGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_update_sql_database( + self, + resource_group_name: str, + account_name: str, + database_name: str, + create_update_sql_database_parameters: Union[_models.SqlDatabaseCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.SqlDatabaseGetResults]: + """Create or update an Azure Cosmos DB SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param create_update_sql_database_parameters: The parameters to provide for the current SQL + database. Is either a SqlDatabaseCreateUpdateParameters type or a IO[bytes] type. Required. + :type create_update_sql_database_parameters: + ~azure.mgmt.cosmosdb.models.SqlDatabaseCreateUpdateParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either SqlDatabaseGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlDatabaseGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.SqlDatabaseGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_update_sql_database_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + create_update_sql_database_parameters=create_update_sql_database_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("SqlDatabaseGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.SqlDatabaseGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.SqlDatabaseGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_sql_database_initial( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_sql_database_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete_sql_database( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes an existing Azure Cosmos DB SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_sql_database_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace_async + async def get_sql_database_throughput( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> _models.ThroughputSettingsGetResults: + """Gets the RUs per second of the SQL database under an existing Azure Cosmos DB database account + with the provided name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: ThroughputSettingsGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + + _request = build_get_sql_database_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _update_sql_database_throughput_initial( + self, + resource_group_name: str, + account_name: str, + database_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(update_throughput_parameters, (IOBase, bytes)): + _content = update_throughput_parameters + else: + _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") + + _request = build_update_sql_database_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_update_sql_database_throughput( + self, + resource_group_name: str, + account_name: str, + database_name: str, + update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param update_throughput_parameters: The parameters to provide for the RUs per second of the + current SQL database. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update_sql_database_throughput( + self, + resource_group_name: str, + account_name: str, + database_name: str, + update_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param update_throughput_parameters: The parameters to provide for the RUs per second of the + current SQL database. Required. + :type update_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update_sql_database_throughput( + self, + resource_group_name: str, + account_name: str, + database_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param update_throughput_parameters: The parameters to provide for the RUs per second of the + current SQL database. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] type. + Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._update_sql_database_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + update_throughput_parameters=update_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _migrate_sql_database_to_autoscale_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_sql_database_to_autoscale_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_migrate_sql_database_to_autoscale( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB SQL database from manual throughput to autoscale. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._migrate_sql_database_to_autoscale_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _migrate_sql_database_to_manual_throughput_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_sql_database_to_manual_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_migrate_sql_database_to_manual_throughput( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB SQL database from autoscale to manual throughput. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._migrate_sql_database_to_manual_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def list_client_encryption_keys( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> AsyncIterable["_models.ClientEncryptionKeyGetResults"]: + """Lists the ClientEncryptionKeys under an existing Azure Cosmos DB SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: An iterator like instance of either ClientEncryptionKeyGetResults or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.ClientEncryptionKeyGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ClientEncryptionKeysListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_client_encryption_keys_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ClientEncryptionKeysListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get_client_encryption_key( + self, + resource_group_name: str, + account_name: str, + database_name: str, + client_encryption_key_name: str, + **kwargs: Any + ) -> _models.ClientEncryptionKeyGetResults: + """Gets the ClientEncryptionKey under an existing Azure Cosmos DB SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param client_encryption_key_name: Cosmos DB ClientEncryptionKey name. Required. + :type client_encryption_key_name: str + :return: ClientEncryptionKeyGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ClientEncryptionKeyGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ClientEncryptionKeyGetResults] = kwargs.pop("cls", None) + + _request = build_get_client_encryption_key_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + client_encryption_key_name=client_encryption_key_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ClientEncryptionKeyGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_update_client_encryption_key_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + client_encryption_key_name: str, + create_update_client_encryption_key_parameters: Union[ + _models.ClientEncryptionKeyCreateUpdateParameters, IO[bytes] + ], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_client_encryption_key_parameters, (IOBase, bytes)): + _content = create_update_client_encryption_key_parameters + else: + _json = self._serialize.body( + create_update_client_encryption_key_parameters, "ClientEncryptionKeyCreateUpdateParameters" + ) + + _request = build_create_update_client_encryption_key_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + client_encryption_key_name=client_encryption_key_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_update_client_encryption_key( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + client_encryption_key_name: str, + create_update_client_encryption_key_parameters: _models.ClientEncryptionKeyCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ClientEncryptionKeyGetResults]: + """Create or update a ClientEncryptionKey. This API is meant to be invoked via tools such as the + Azure Powershell (instead of directly). + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param client_encryption_key_name: Cosmos DB ClientEncryptionKey name. Required. + :type client_encryption_key_name: str + :param create_update_client_encryption_key_parameters: The parameters to provide for the client + encryption key. Required. + :type create_update_client_encryption_key_parameters: + ~azure.mgmt.cosmosdb.models.ClientEncryptionKeyCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ClientEncryptionKeyGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ClientEncryptionKeyGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_update_client_encryption_key( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + client_encryption_key_name: str, + create_update_client_encryption_key_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ClientEncryptionKeyGetResults]: + """Create or update a ClientEncryptionKey. This API is meant to be invoked via tools such as the + Azure Powershell (instead of directly). + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param client_encryption_key_name: Cosmos DB ClientEncryptionKey name. Required. + :type client_encryption_key_name: str + :param create_update_client_encryption_key_parameters: The parameters to provide for the client + encryption key. Required. + :type create_update_client_encryption_key_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ClientEncryptionKeyGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ClientEncryptionKeyGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_update_client_encryption_key( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + client_encryption_key_name: str, + create_update_client_encryption_key_parameters: Union[ + _models.ClientEncryptionKeyCreateUpdateParameters, IO[bytes] + ], + **kwargs: Any + ) -> AsyncLROPoller[_models.ClientEncryptionKeyGetResults]: + """Create or update a ClientEncryptionKey. This API is meant to be invoked via tools such as the + Azure Powershell (instead of directly). + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param client_encryption_key_name: Cosmos DB ClientEncryptionKey name. Required. + :type client_encryption_key_name: str + :param create_update_client_encryption_key_parameters: The parameters to provide for the client + encryption key. Is either a ClientEncryptionKeyCreateUpdateParameters type or a IO[bytes] type. + Required. + :type create_update_client_encryption_key_parameters: + ~azure.mgmt.cosmosdb.models.ClientEncryptionKeyCreateUpdateParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either ClientEncryptionKeyGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ClientEncryptionKeyGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ClientEncryptionKeyGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_update_client_encryption_key_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + client_encryption_key_name=client_encryption_key_name, + create_update_client_encryption_key_parameters=create_update_client_encryption_key_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ClientEncryptionKeyGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ClientEncryptionKeyGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ClientEncryptionKeyGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def list_sql_containers( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> AsyncIterable["_models.SqlContainerGetResults"]: + """Lists the SQL container under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: An iterator like instance of either SqlContainerGetResults or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.SqlContainerGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SqlContainerListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_sql_containers_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("SqlContainerListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get_sql_container( + self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any + ) -> _models.SqlContainerGetResults: + """Gets the SQL container under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :return: SqlContainerGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.SqlContainerGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SqlContainerGetResults] = kwargs.pop("cls", None) + + _request = build_get_sql_container_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("SqlContainerGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_update_sql_container_initial( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + create_update_sql_container_parameters: Union[_models.SqlContainerCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_sql_container_parameters, (IOBase, bytes)): + _content = create_update_sql_container_parameters + else: + _json = self._serialize.body(create_update_sql_container_parameters, "SqlContainerCreateUpdateParameters") + + _request = build_create_update_sql_container_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_update_sql_container( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + create_update_sql_container_parameters: _models.SqlContainerCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.SqlContainerGetResults]: + """Create or update an Azure Cosmos DB SQL container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param create_update_sql_container_parameters: The parameters to provide for the current SQL + container. Required. + :type create_update_sql_container_parameters: + ~azure.mgmt.cosmosdb.models.SqlContainerCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either SqlContainerGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlContainerGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_update_sql_container( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + create_update_sql_container_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.SqlContainerGetResults]: + """Create or update an Azure Cosmos DB SQL container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param create_update_sql_container_parameters: The parameters to provide for the current SQL + container. Required. + :type create_update_sql_container_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either SqlContainerGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlContainerGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_update_sql_container( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + create_update_sql_container_parameters: Union[_models.SqlContainerCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.SqlContainerGetResults]: + """Create or update an Azure Cosmos DB SQL container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param create_update_sql_container_parameters: The parameters to provide for the current SQL + container. Is either a SqlContainerCreateUpdateParameters type or a IO[bytes] type. Required. + :type create_update_sql_container_parameters: + ~azure.mgmt.cosmosdb.models.SqlContainerCreateUpdateParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either SqlContainerGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlContainerGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.SqlContainerGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_update_sql_container_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + create_update_sql_container_parameters=create_update_sql_container_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("SqlContainerGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.SqlContainerGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.SqlContainerGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_sql_container_initial( + self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_sql_container_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete_sql_container( + self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes an existing Azure Cosmos DB SQL container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_sql_container_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + async def _sql_database_partition_merge_initial( + self, + resource_group_name: str, + account_name: str, + database_name: str, + merge_parameters: Union[_models.MergeParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(merge_parameters, (IOBase, bytes)): + _content = merge_parameters + else: + _json = self._serialize.body(merge_parameters, "MergeParameters") + + _request = build_sql_database_partition_merge_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_sql_database_partition_merge( + self, + resource_group_name: str, + account_name: str, + database_name: str, + merge_parameters: _models.MergeParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]: + """Merges the partitions of a SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param merge_parameters: The parameters for the merge operation. Required. + :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionStorageInfoCollection or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_sql_database_partition_merge( + self, + resource_group_name: str, + account_name: str, + database_name: str, + merge_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]: + """Merges the partitions of a SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param merge_parameters: The parameters for the merge operation. Required. + :type merge_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionStorageInfoCollection or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_sql_database_partition_merge( + self, + resource_group_name: str, + account_name: str, + database_name: str, + merge_parameters: Union[_models.MergeParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]: + """Merges the partitions of a SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param merge_parameters: The parameters for the merge operation. Is either a MergeParameters + type or a IO[bytes] type. Required. + :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionStorageInfoCollection or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PhysicalPartitionStorageInfoCollection] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._sql_database_partition_merge_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + merge_parameters=merge_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("PhysicalPartitionStorageInfoCollection", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _list_sql_container_partition_merge_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + merge_parameters: Union[_models.MergeParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(merge_parameters, (IOBase, bytes)): + _content = merge_parameters + else: + _json = self._serialize.body(merge_parameters, "MergeParameters") + + _request = build_list_sql_container_partition_merge_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_list_sql_container_partition_merge( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + merge_parameters: _models.MergeParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]: + """Merges the partitions of a SQL Container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param merge_parameters: The parameters for the merge operation. Required. + :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionStorageInfoCollection or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_list_sql_container_partition_merge( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + merge_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]: + """Merges the partitions of a SQL Container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param merge_parameters: The parameters for the merge operation. Required. + :type merge_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionStorageInfoCollection or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_list_sql_container_partition_merge( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + merge_parameters: Union[_models.MergeParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]: + """Merges the partitions of a SQL Container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param merge_parameters: The parameters for the merge operation. Is either a MergeParameters + type or a IO[bytes] type. Required. + :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionStorageInfoCollection or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PhysicalPartitionStorageInfoCollection] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._list_sql_container_partition_merge_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + merge_parameters=merge_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("PhysicalPartitionStorageInfoCollection", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace_async + async def get_sql_container_throughput( + self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any + ) -> _models.ThroughputSettingsGetResults: + """Gets the RUs per second of the SQL container under an existing Azure Cosmos DB database + account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :return: ThroughputSettingsGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + + _request = build_get_sql_container_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _update_sql_container_throughput_initial( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(update_throughput_parameters, (IOBase, bytes)): + _content = update_throughput_parameters + else: + _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") + + _request = build_update_sql_container_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_update_sql_container_throughput( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB SQL container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param update_throughput_parameters: The parameters to provide for the RUs per second of the + current SQL container. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update_sql_container_throughput( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + update_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB SQL container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param update_throughput_parameters: The parameters to provide for the RUs per second of the + current SQL container. Required. + :type update_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update_sql_container_throughput( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB SQL container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param update_throughput_parameters: The parameters to provide for the RUs per second of the + current SQL container. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] type. + Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._update_sql_container_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + update_throughput_parameters=update_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _migrate_sql_container_to_autoscale_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_sql_container_to_autoscale_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_migrate_sql_container_to_autoscale( + self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB SQL container from manual throughput to autoscale. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._migrate_sql_container_to_autoscale_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _migrate_sql_container_to_manual_throughput_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_sql_container_to_manual_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_migrate_sql_container_to_manual_throughput( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB SQL container from autoscale to manual throughput. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._migrate_sql_container_to_manual_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _sql_database_retrieve_throughput_distribution_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(retrieve_throughput_parameters, (IOBase, bytes)): + _content = retrieve_throughput_parameters + else: + _json = self._serialize.body(retrieve_throughput_parameters, "RetrieveThroughputParameters") + + _request = build_sql_database_retrieve_throughput_distribution_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_sql_database_retrieve_throughput_distribution( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + retrieve_throughput_parameters: _models.RetrieveThroughputParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Retrieve throughput distribution for an Azure Cosmos DB SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput + distribution for the current SQL database. Required. + :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionThroughputInfoResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_sql_database_retrieve_throughput_distribution( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + retrieve_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Retrieve throughput distribution for an Azure Cosmos DB SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput + distribution for the current SQL database. Required. + :type retrieve_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionThroughputInfoResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_sql_database_retrieve_throughput_distribution( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Retrieve throughput distribution for an Azure Cosmos DB SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput + distribution for the current SQL database. Is either a RetrieveThroughputParameters type or a + IO[bytes] type. Required. + :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters + or IO[bytes] + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionThroughputInfoResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._sql_database_retrieve_throughput_distribution_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + retrieve_throughput_parameters=retrieve_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _sql_database_redistribute_throughput_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(redistribute_throughput_parameters, (IOBase, bytes)): + _content = redistribute_throughput_parameters + else: + _json = self._serialize.body(redistribute_throughput_parameters, "RedistributeThroughputParameters") + + _request = build_sql_database_redistribute_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_sql_database_redistribute_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + redistribute_throughput_parameters: _models.RedistributeThroughputParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Redistribute throughput for an Azure Cosmos DB SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param redistribute_throughput_parameters: The parameters to provide for redistributing + throughput for the current SQL database. Required. + :type redistribute_throughput_parameters: + ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionThroughputInfoResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_sql_database_redistribute_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + redistribute_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Redistribute throughput for an Azure Cosmos DB SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param redistribute_throughput_parameters: The parameters to provide for redistributing + throughput for the current SQL database. Required. + :type redistribute_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionThroughputInfoResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_sql_database_redistribute_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Redistribute throughput for an Azure Cosmos DB SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param redistribute_throughput_parameters: The parameters to provide for redistributing + throughput for the current SQL database. Is either a RedistributeThroughputParameters type or a + IO[bytes] type. Required. + :type redistribute_throughput_parameters: + ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionThroughputInfoResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._sql_database_redistribute_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + redistribute_throughput_parameters=redistribute_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _sql_container_retrieve_throughput_distribution_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(retrieve_throughput_parameters, (IOBase, bytes)): + _content = retrieve_throughput_parameters + else: + _json = self._serialize.body(retrieve_throughput_parameters, "RetrieveThroughputParameters") + + _request = build_sql_container_retrieve_throughput_distribution_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_sql_container_retrieve_throughput_distribution( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + retrieve_throughput_parameters: _models.RetrieveThroughputParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Retrieve throughput distribution for an Azure Cosmos DB SQL container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput + distribution for the current SQL container. Required. + :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionThroughputInfoResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_sql_container_retrieve_throughput_distribution( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + retrieve_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Retrieve throughput distribution for an Azure Cosmos DB SQL container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput + distribution for the current SQL container. Required. + :type retrieve_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionThroughputInfoResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_sql_container_retrieve_throughput_distribution( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Retrieve throughput distribution for an Azure Cosmos DB SQL container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput + distribution for the current SQL container. Is either a RetrieveThroughputParameters type or a + IO[bytes] type. Required. + :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters + or IO[bytes] + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionThroughputInfoResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._sql_container_retrieve_throughput_distribution_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + retrieve_throughput_parameters=retrieve_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _sql_container_redistribute_throughput_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(redistribute_throughput_parameters, (IOBase, bytes)): + _content = redistribute_throughput_parameters + else: + _json = self._serialize.body(redistribute_throughput_parameters, "RedistributeThroughputParameters") + + _request = build_sql_container_redistribute_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_sql_container_redistribute_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + redistribute_throughput_parameters: _models.RedistributeThroughputParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Redistribute throughput for an Azure Cosmos DB SQL container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param redistribute_throughput_parameters: The parameters to provide for redistributing + throughput for the current SQL container. Required. + :type redistribute_throughput_parameters: + ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionThroughputInfoResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_sql_container_redistribute_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + redistribute_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Redistribute throughput for an Azure Cosmos DB SQL container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param redistribute_throughput_parameters: The parameters to provide for redistributing + throughput for the current SQL container. Required. + :type redistribute_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionThroughputInfoResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_sql_container_redistribute_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Redistribute throughput for an Azure Cosmos DB SQL container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param redistribute_throughput_parameters: The parameters to provide for redistributing + throughput for the current SQL container. Is either a RedistributeThroughputParameters type or + a IO[bytes] type. Required. + :type redistribute_throughput_parameters: + ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either + PhysicalPartitionThroughputInfoResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._sql_container_redistribute_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + redistribute_throughput_parameters=redistribute_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def list_sql_stored_procedures( + self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any + ) -> AsyncIterable["_models.SqlStoredProcedureGetResults"]: + """Lists the SQL storedProcedure under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :return: An iterator like instance of either SqlStoredProcedureGetResults or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.SqlStoredProcedureGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SqlStoredProcedureListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_sql_stored_procedures_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("SqlStoredProcedureListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get_sql_stored_procedure( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + stored_procedure_name: str, + **kwargs: Any + ) -> _models.SqlStoredProcedureGetResults: + """Gets the SQL storedProcedure under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param stored_procedure_name: Cosmos DB storedProcedure name. Required. + :type stored_procedure_name: str + :return: SqlStoredProcedureGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.SqlStoredProcedureGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SqlStoredProcedureGetResults] = kwargs.pop("cls", None) + + _request = build_get_sql_stored_procedure_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + stored_procedure_name=stored_procedure_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("SqlStoredProcedureGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_update_sql_stored_procedure_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + stored_procedure_name: str, + create_update_sql_stored_procedure_parameters: Union[ + _models.SqlStoredProcedureCreateUpdateParameters, IO[bytes] + ], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_sql_stored_procedure_parameters, (IOBase, bytes)): + _content = create_update_sql_stored_procedure_parameters + else: + _json = self._serialize.body( + create_update_sql_stored_procedure_parameters, "SqlStoredProcedureCreateUpdateParameters" + ) + + _request = build_create_update_sql_stored_procedure_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + stored_procedure_name=stored_procedure_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_update_sql_stored_procedure( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + stored_procedure_name: str, + create_update_sql_stored_procedure_parameters: _models.SqlStoredProcedureCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.SqlStoredProcedureGetResults]: + """Create or update an Azure Cosmos DB SQL storedProcedure. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param stored_procedure_name: Cosmos DB storedProcedure name. Required. + :type stored_procedure_name: str + :param create_update_sql_stored_procedure_parameters: The parameters to provide for the current + SQL storedProcedure. Required. + :type create_update_sql_stored_procedure_parameters: + ~azure.mgmt.cosmosdb.models.SqlStoredProcedureCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either SqlStoredProcedureGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlStoredProcedureGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_update_sql_stored_procedure( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + stored_procedure_name: str, + create_update_sql_stored_procedure_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.SqlStoredProcedureGetResults]: + """Create or update an Azure Cosmos DB SQL storedProcedure. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param stored_procedure_name: Cosmos DB storedProcedure name. Required. + :type stored_procedure_name: str + :param create_update_sql_stored_procedure_parameters: The parameters to provide for the current + SQL storedProcedure. Required. + :type create_update_sql_stored_procedure_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either SqlStoredProcedureGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlStoredProcedureGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_update_sql_stored_procedure( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + stored_procedure_name: str, + create_update_sql_stored_procedure_parameters: Union[ + _models.SqlStoredProcedureCreateUpdateParameters, IO[bytes] + ], + **kwargs: Any + ) -> AsyncLROPoller[_models.SqlStoredProcedureGetResults]: + """Create or update an Azure Cosmos DB SQL storedProcedure. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param stored_procedure_name: Cosmos DB storedProcedure name. Required. + :type stored_procedure_name: str + :param create_update_sql_stored_procedure_parameters: The parameters to provide for the current + SQL storedProcedure. Is either a SqlStoredProcedureCreateUpdateParameters type or a IO[bytes] + type. Required. + :type create_update_sql_stored_procedure_parameters: + ~azure.mgmt.cosmosdb.models.SqlStoredProcedureCreateUpdateParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either SqlStoredProcedureGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlStoredProcedureGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.SqlStoredProcedureGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_update_sql_stored_procedure_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + stored_procedure_name=stored_procedure_name, + create_update_sql_stored_procedure_parameters=create_update_sql_stored_procedure_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("SqlStoredProcedureGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.SqlStoredProcedureGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.SqlStoredProcedureGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_sql_stored_procedure_initial( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + stored_procedure_name: str, + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_sql_stored_procedure_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + stored_procedure_name=stored_procedure_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete_sql_stored_procedure( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + stored_procedure_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes an existing Azure Cosmos DB SQL storedProcedure. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param stored_procedure_name: Cosmos DB storedProcedure name. Required. + :type stored_procedure_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_sql_stored_procedure_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + stored_procedure_name=stored_procedure_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def list_sql_user_defined_functions( + self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any + ) -> AsyncIterable["_models.SqlUserDefinedFunctionGetResults"]: + """Lists the SQL userDefinedFunction under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :return: An iterator like instance of either SqlUserDefinedFunctionGetResults or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SqlUserDefinedFunctionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_sql_user_defined_functions_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("SqlUserDefinedFunctionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get_sql_user_defined_function( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + user_defined_function_name: str, + **kwargs: Any + ) -> _models.SqlUserDefinedFunctionGetResults: + """Gets the SQL userDefinedFunction under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param user_defined_function_name: Cosmos DB userDefinedFunction name. Required. + :type user_defined_function_name: str + :return: SqlUserDefinedFunctionGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SqlUserDefinedFunctionGetResults] = kwargs.pop("cls", None) + + _request = build_get_sql_user_defined_function_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + user_defined_function_name=user_defined_function_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("SqlUserDefinedFunctionGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_update_sql_user_defined_function_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + user_defined_function_name: str, + create_update_sql_user_defined_function_parameters: Union[ + _models.SqlUserDefinedFunctionCreateUpdateParameters, IO[bytes] + ], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_sql_user_defined_function_parameters, (IOBase, bytes)): + _content = create_update_sql_user_defined_function_parameters + else: + _json = self._serialize.body( + create_update_sql_user_defined_function_parameters, "SqlUserDefinedFunctionCreateUpdateParameters" + ) + + _request = build_create_update_sql_user_defined_function_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + user_defined_function_name=user_defined_function_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_update_sql_user_defined_function( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + user_defined_function_name: str, + create_update_sql_user_defined_function_parameters: _models.SqlUserDefinedFunctionCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.SqlUserDefinedFunctionGetResults]: + """Create or update an Azure Cosmos DB SQL userDefinedFunction. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param user_defined_function_name: Cosmos DB userDefinedFunction name. Required. + :type user_defined_function_name: str + :param create_update_sql_user_defined_function_parameters: The parameters to provide for the + current SQL userDefinedFunction. Required. + :type create_update_sql_user_defined_function_parameters: + ~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either SqlUserDefinedFunctionGetResults or + the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_update_sql_user_defined_function( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + user_defined_function_name: str, + create_update_sql_user_defined_function_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.SqlUserDefinedFunctionGetResults]: + """Create or update an Azure Cosmos DB SQL userDefinedFunction. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param user_defined_function_name: Cosmos DB userDefinedFunction name. Required. + :type user_defined_function_name: str + :param create_update_sql_user_defined_function_parameters: The parameters to provide for the + current SQL userDefinedFunction. Required. + :type create_update_sql_user_defined_function_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either SqlUserDefinedFunctionGetResults or + the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_update_sql_user_defined_function( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + user_defined_function_name: str, + create_update_sql_user_defined_function_parameters: Union[ + _models.SqlUserDefinedFunctionCreateUpdateParameters, IO[bytes] + ], + **kwargs: Any + ) -> AsyncLROPoller[_models.SqlUserDefinedFunctionGetResults]: + """Create or update an Azure Cosmos DB SQL userDefinedFunction. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param user_defined_function_name: Cosmos DB userDefinedFunction name. Required. + :type user_defined_function_name: str + :param create_update_sql_user_defined_function_parameters: The parameters to provide for the + current SQL userDefinedFunction. Is either a SqlUserDefinedFunctionCreateUpdateParameters type + or a IO[bytes] type. Required. + :type create_update_sql_user_defined_function_parameters: + ~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionCreateUpdateParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either SqlUserDefinedFunctionGetResults or + the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.SqlUserDefinedFunctionGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_update_sql_user_defined_function_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + user_defined_function_name=user_defined_function_name, + create_update_sql_user_defined_function_parameters=create_update_sql_user_defined_function_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("SqlUserDefinedFunctionGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.SqlUserDefinedFunctionGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.SqlUserDefinedFunctionGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_sql_user_defined_function_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + user_defined_function_name: str, + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_sql_user_defined_function_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + user_defined_function_name=user_defined_function_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete_sql_user_defined_function( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + user_defined_function_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes an existing Azure Cosmos DB SQL userDefinedFunction. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param user_defined_function_name: Cosmos DB userDefinedFunction name. Required. + :type user_defined_function_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_sql_user_defined_function_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + user_defined_function_name=user_defined_function_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def list_sql_triggers( + self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any + ) -> AsyncIterable["_models.SqlTriggerGetResults"]: + """Lists the SQL trigger under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :return: An iterator like instance of either SqlTriggerGetResults or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.SqlTriggerGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SqlTriggerListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_sql_triggers_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("SqlTriggerListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get_sql_trigger( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + trigger_name: str, + **kwargs: Any + ) -> _models.SqlTriggerGetResults: + """Gets the SQL trigger under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param trigger_name: Cosmos DB trigger name. Required. + :type trigger_name: str + :return: SqlTriggerGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.SqlTriggerGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SqlTriggerGetResults] = kwargs.pop("cls", None) + + _request = build_get_sql_trigger_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + trigger_name=trigger_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("SqlTriggerGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_update_sql_trigger_initial( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + trigger_name: str, + create_update_sql_trigger_parameters: Union[_models.SqlTriggerCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_sql_trigger_parameters, (IOBase, bytes)): + _content = create_update_sql_trigger_parameters + else: + _json = self._serialize.body(create_update_sql_trigger_parameters, "SqlTriggerCreateUpdateParameters") + + _request = build_create_update_sql_trigger_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + trigger_name=trigger_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_update_sql_trigger( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + trigger_name: str, + create_update_sql_trigger_parameters: _models.SqlTriggerCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.SqlTriggerGetResults]: + """Create or update an Azure Cosmos DB SQL trigger. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param trigger_name: Cosmos DB trigger name. Required. + :type trigger_name: str + :param create_update_sql_trigger_parameters: The parameters to provide for the current SQL + trigger. Required. + :type create_update_sql_trigger_parameters: + ~azure.mgmt.cosmosdb.models.SqlTriggerCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either SqlTriggerGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlTriggerGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_update_sql_trigger( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + trigger_name: str, + create_update_sql_trigger_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.SqlTriggerGetResults]: + """Create or update an Azure Cosmos DB SQL trigger. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param trigger_name: Cosmos DB trigger name. Required. + :type trigger_name: str + :param create_update_sql_trigger_parameters: The parameters to provide for the current SQL + trigger. Required. + :type create_update_sql_trigger_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either SqlTriggerGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlTriggerGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_update_sql_trigger( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + trigger_name: str, + create_update_sql_trigger_parameters: Union[_models.SqlTriggerCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.SqlTriggerGetResults]: + """Create or update an Azure Cosmos DB SQL trigger. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param trigger_name: Cosmos DB trigger name. Required. + :type trigger_name: str + :param create_update_sql_trigger_parameters: The parameters to provide for the current SQL + trigger. Is either a SqlTriggerCreateUpdateParameters type or a IO[bytes] type. Required. + :type create_update_sql_trigger_parameters: + ~azure.mgmt.cosmosdb.models.SqlTriggerCreateUpdateParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either SqlTriggerGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlTriggerGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.SqlTriggerGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_update_sql_trigger_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + trigger_name=trigger_name, + create_update_sql_trigger_parameters=create_update_sql_trigger_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("SqlTriggerGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.SqlTriggerGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.SqlTriggerGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_sql_trigger_initial( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + trigger_name: str, + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_sql_trigger_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + trigger_name=trigger_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete_sql_trigger( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + trigger_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes an existing Azure Cosmos DB SQL trigger. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param trigger_name: Cosmos DB trigger name. Required. + :type trigger_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_sql_trigger_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + trigger_name=trigger_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace_async + async def get_sql_role_definition( + self, role_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any + ) -> _models.SqlRoleDefinitionGetResults: + """Retrieves the properties of an existing Azure Cosmos DB SQL Role Definition with the given Id. + + :param role_definition_id: The GUID for the Role Definition. Required. + :type role_definition_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: SqlRoleDefinitionGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.SqlRoleDefinitionGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SqlRoleDefinitionGetResults] = kwargs.pop("cls", None) + + _request = build_get_sql_role_definition_request( + role_definition_id=role_definition_id, + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("SqlRoleDefinitionGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_update_sql_role_definition_initial( # pylint: disable=name-too-long + self, + role_definition_id: str, + resource_group_name: str, + account_name: str, + create_update_sql_role_definition_parameters: Union[_models.SqlRoleDefinitionCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_sql_role_definition_parameters, (IOBase, bytes)): + _content = create_update_sql_role_definition_parameters + else: + _json = self._serialize.body( + create_update_sql_role_definition_parameters, "SqlRoleDefinitionCreateUpdateParameters" + ) + + _request = build_create_update_sql_role_definition_request( + role_definition_id=role_definition_id, + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_update_sql_role_definition( + self, + role_definition_id: str, + resource_group_name: str, + account_name: str, + create_update_sql_role_definition_parameters: _models.SqlRoleDefinitionCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.SqlRoleDefinitionGetResults]: + """Creates or updates an Azure Cosmos DB SQL Role Definition. + + :param role_definition_id: The GUID for the Role Definition. Required. + :type role_definition_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param create_update_sql_role_definition_parameters: The properties required to create or + update a Role Definition. Required. + :type create_update_sql_role_definition_parameters: + ~azure.mgmt.cosmosdb.models.SqlRoleDefinitionCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either SqlRoleDefinitionGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlRoleDefinitionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_update_sql_role_definition( + self, + role_definition_id: str, + resource_group_name: str, + account_name: str, + create_update_sql_role_definition_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.SqlRoleDefinitionGetResults]: + """Creates or updates an Azure Cosmos DB SQL Role Definition. + + :param role_definition_id: The GUID for the Role Definition. Required. + :type role_definition_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param create_update_sql_role_definition_parameters: The properties required to create or + update a Role Definition. Required. + :type create_update_sql_role_definition_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either SqlRoleDefinitionGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlRoleDefinitionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_update_sql_role_definition( + self, + role_definition_id: str, + resource_group_name: str, + account_name: str, + create_update_sql_role_definition_parameters: Union[_models.SqlRoleDefinitionCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.SqlRoleDefinitionGetResults]: + """Creates or updates an Azure Cosmos DB SQL Role Definition. + + :param role_definition_id: The GUID for the Role Definition. Required. + :type role_definition_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param create_update_sql_role_definition_parameters: The properties required to create or + update a Role Definition. Is either a SqlRoleDefinitionCreateUpdateParameters type or a + IO[bytes] type. Required. + :type create_update_sql_role_definition_parameters: + ~azure.mgmt.cosmosdb.models.SqlRoleDefinitionCreateUpdateParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either SqlRoleDefinitionGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlRoleDefinitionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.SqlRoleDefinitionGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_update_sql_role_definition_initial( + role_definition_id=role_definition_id, + resource_group_name=resource_group_name, + account_name=account_name, + create_update_sql_role_definition_parameters=create_update_sql_role_definition_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("SqlRoleDefinitionGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.SqlRoleDefinitionGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.SqlRoleDefinitionGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_sql_role_definition_initial( + self, role_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_sql_role_definition_request( + role_definition_id=role_definition_id, + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete_sql_role_definition( + self, role_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes an existing Azure Cosmos DB SQL Role Definition. + + :param role_definition_id: The GUID for the Role Definition. Required. + :type role_definition_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_sql_role_definition_initial( + role_definition_id=role_definition_id, + resource_group_name=resource_group_name, + account_name=account_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def list_sql_role_definitions( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> AsyncIterable["_models.SqlRoleDefinitionGetResults"]: + """Retrieves the list of all Azure Cosmos DB SQL Role Definitions. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either SqlRoleDefinitionGetResults or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.SqlRoleDefinitionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SqlRoleDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_sql_role_definitions_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("SqlRoleDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get_sql_role_assignment( + self, role_assignment_id: str, resource_group_name: str, account_name: str, **kwargs: Any + ) -> _models.SqlRoleAssignmentGetResults: + """Retrieves the properties of an existing Azure Cosmos DB SQL Role Assignment with the given Id. + + :param role_assignment_id: The GUID for the Role Assignment. Required. + :type role_assignment_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: SqlRoleAssignmentGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.SqlRoleAssignmentGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SqlRoleAssignmentGetResults] = kwargs.pop("cls", None) + + _request = build_get_sql_role_assignment_request( + role_assignment_id=role_assignment_id, + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("SqlRoleAssignmentGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_update_sql_role_assignment_initial( # pylint: disable=name-too-long + self, + role_assignment_id: str, + resource_group_name: str, + account_name: str, + create_update_sql_role_assignment_parameters: Union[_models.SqlRoleAssignmentCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_sql_role_assignment_parameters, (IOBase, bytes)): + _content = create_update_sql_role_assignment_parameters + else: + _json = self._serialize.body( + create_update_sql_role_assignment_parameters, "SqlRoleAssignmentCreateUpdateParameters" + ) + + _request = build_create_update_sql_role_assignment_request( + role_assignment_id=role_assignment_id, + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_update_sql_role_assignment( + self, + role_assignment_id: str, + resource_group_name: str, + account_name: str, + create_update_sql_role_assignment_parameters: _models.SqlRoleAssignmentCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.SqlRoleAssignmentGetResults]: + """Creates or updates an Azure Cosmos DB SQL Role Assignment. + + :param role_assignment_id: The GUID for the Role Assignment. Required. + :type role_assignment_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param create_update_sql_role_assignment_parameters: The properties required to create or + update a Role Assignment. Required. + :type create_update_sql_role_assignment_parameters: + ~azure.mgmt.cosmosdb.models.SqlRoleAssignmentCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either SqlRoleAssignmentGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlRoleAssignmentGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_update_sql_role_assignment( + self, + role_assignment_id: str, + resource_group_name: str, + account_name: str, + create_update_sql_role_assignment_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.SqlRoleAssignmentGetResults]: + """Creates or updates an Azure Cosmos DB SQL Role Assignment. + + :param role_assignment_id: The GUID for the Role Assignment. Required. + :type role_assignment_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param create_update_sql_role_assignment_parameters: The properties required to create or + update a Role Assignment. Required. + :type create_update_sql_role_assignment_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either SqlRoleAssignmentGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlRoleAssignmentGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_update_sql_role_assignment( + self, + role_assignment_id: str, + resource_group_name: str, + account_name: str, + create_update_sql_role_assignment_parameters: Union[_models.SqlRoleAssignmentCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.SqlRoleAssignmentGetResults]: + """Creates or updates an Azure Cosmos DB SQL Role Assignment. + + :param role_assignment_id: The GUID for the Role Assignment. Required. + :type role_assignment_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param create_update_sql_role_assignment_parameters: The properties required to create or + update a Role Assignment. Is either a SqlRoleAssignmentCreateUpdateParameters type or a + IO[bytes] type. Required. + :type create_update_sql_role_assignment_parameters: + ~azure.mgmt.cosmosdb.models.SqlRoleAssignmentCreateUpdateParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either SqlRoleAssignmentGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.SqlRoleAssignmentGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.SqlRoleAssignmentGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_update_sql_role_assignment_initial( + role_assignment_id=role_assignment_id, + resource_group_name=resource_group_name, + account_name=account_name, + create_update_sql_role_assignment_parameters=create_update_sql_role_assignment_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("SqlRoleAssignmentGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.SqlRoleAssignmentGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.SqlRoleAssignmentGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_sql_role_assignment_initial( + self, role_assignment_id: str, resource_group_name: str, account_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_sql_role_assignment_request( + role_assignment_id=role_assignment_id, + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete_sql_role_assignment( + self, role_assignment_id: str, resource_group_name: str, account_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes an existing Azure Cosmos DB SQL Role Assignment. + + :param role_assignment_id: The GUID for the Role Assignment. Required. + :type role_assignment_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_sql_role_assignment_initial( + role_assignment_id=role_assignment_id, + resource_group_name=resource_group_name, + account_name=account_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def list_sql_role_assignments( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> AsyncIterable["_models.SqlRoleAssignmentGetResults"]: + """Retrieves the list of all Azure Cosmos DB SQL Role Assignments. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either SqlRoleAssignmentGetResults or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.SqlRoleAssignmentGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SqlRoleAssignmentListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_sql_role_assignments_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("SqlRoleAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + async def _retrieve_continuous_backup_information_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(location, (IOBase, bytes)): + _content = location + else: + _json = self._serialize.body(location, "ContinuousBackupRestoreLocation") + + _request = build_retrieve_continuous_backup_information_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + location: _models.ContinuousBackupRestoreLocation, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.BackupInformation]: + """Retrieves continuous backup information for a container resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param location: The name of the continuous backup restore location. Required. + :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either BackupInformation or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + location: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.BackupInformation]: + """Retrieves continuous backup information for a container resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param location: The name of the continuous backup restore location. Required. + :type location: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either BackupInformation or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.BackupInformation]: + """Retrieves continuous backup information for a container resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param location: The name of the continuous backup restore location. Is either a + ContinuousBackupRestoreLocation type or a IO[bytes] type. Required. + :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation or IO[bytes] + :return: An instance of AsyncLROPoller that returns either BackupInformation or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.BackupInformation] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._retrieve_continuous_backup_information_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + location=location, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("BackupInformation", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.BackupInformation].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.BackupInformation]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_table_resources_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_table_resources_operations.py index 85827241ee4..f1f8f4a797c 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_table_resources_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_table_resources_operations.py @@ -1,1275 +1,1275 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling - -from ... import models as _models -from ...operations._table_resources_operations import ( - build_create_update_table_request, - build_delete_table_request, - build_get_table_request, - build_get_table_throughput_request, - build_list_tables_request, - build_migrate_table_to_autoscale_request, - build_migrate_table_to_manual_throughput_request, - build_retrieve_continuous_backup_information_request, - build_update_table_throughput_request, -) - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class TableResourcesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`table_resources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_tables( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> AsyncIterable["_models.TableGetResults"]: - """Lists the Tables under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either TableGetResults or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.TableGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.TableListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_tables_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("TableListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get_table( - self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any - ) -> _models.TableGetResults: - """Gets the Tables under an existing Azure Cosmos DB database account with the provided name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :return: TableGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.TableGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.TableGetResults] = kwargs.pop("cls", None) - - _request = build_get_table_request( - resource_group_name=resource_group_name, - account_name=account_name, - table_name=table_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("TableGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _create_update_table_initial( - self, - resource_group_name: str, - account_name: str, - table_name: str, - create_update_table_parameters: Union[_models.TableCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_table_parameters, (IOBase, bytes)): - _content = create_update_table_parameters - else: - _json = self._serialize.body(create_update_table_parameters, "TableCreateUpdateParameters") - - _request = build_create_update_table_request( - resource_group_name=resource_group_name, - account_name=account_name, - table_name=table_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_update_table( - self, - resource_group_name: str, - account_name: str, - table_name: str, - create_update_table_parameters: _models.TableCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.TableGetResults]: - """Create or update an Azure Cosmos DB Table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :param create_update_table_parameters: The parameters to provide for the current Table. - Required. - :type create_update_table_parameters: ~azure.mgmt.cosmosdb.models.TableCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either TableGetResults or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.TableGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_update_table( - self, - resource_group_name: str, - account_name: str, - table_name: str, - create_update_table_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.TableGetResults]: - """Create or update an Azure Cosmos DB Table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :param create_update_table_parameters: The parameters to provide for the current Table. - Required. - :type create_update_table_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either TableGetResults or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.TableGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_update_table( - self, - resource_group_name: str, - account_name: str, - table_name: str, - create_update_table_parameters: Union[_models.TableCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.TableGetResults]: - """Create or update an Azure Cosmos DB Table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :param create_update_table_parameters: The parameters to provide for the current Table. Is - either a TableCreateUpdateParameters type or a IO[bytes] type. Required. - :type create_update_table_parameters: ~azure.mgmt.cosmosdb.models.TableCreateUpdateParameters - or IO[bytes] - :return: An instance of AsyncLROPoller that returns either TableGetResults or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.TableGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.TableGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_update_table_initial( - resource_group_name=resource_group_name, - account_name=account_name, - table_name=table_name, - create_update_table_parameters=create_update_table_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("TableGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.TableGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.TableGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _delete_table_initial( - self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_table_request( - resource_group_name=resource_group_name, - account_name=account_name, - table_name=table_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete_table( - self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes an existing Azure Cosmos DB Table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_table_initial( - resource_group_name=resource_group_name, - account_name=account_name, - table_name=table_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace_async - async def get_table_throughput( - self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any - ) -> _models.ThroughputSettingsGetResults: - """Gets the RUs per second of the Table under an existing Azure Cosmos DB database account with - the provided name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :return: ThroughputSettingsGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - - _request = build_get_table_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - table_name=table_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _update_table_throughput_initial( - self, - resource_group_name: str, - account_name: str, - table_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(update_throughput_parameters, (IOBase, bytes)): - _content = update_throughput_parameters - else: - _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") - - _request = build_update_table_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - table_name=table_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_update_table_throughput( - self, - resource_group_name: str, - account_name: str, - table_name: str, - update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :param update_throughput_parameters: The parameters to provide for the RUs per second of the - current Table. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_update_table_throughput( - self, - resource_group_name: str, - account_name: str, - table_name: str, - update_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :param update_throughput_parameters: The parameters to provide for the RUs per second of the - current Table. Required. - :type update_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_update_table_throughput( - self, - resource_group_name: str, - account_name: str, - table_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :param update_throughput_parameters: The parameters to provide for the RUs per second of the - current Table. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] type. - Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._update_table_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - table_name=table_name, - update_throughput_parameters=update_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _migrate_table_to_autoscale_initial( - self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_table_to_autoscale_request( - resource_group_name=resource_group_name, - account_name=account_name, - table_name=table_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_migrate_table_to_autoscale( - self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB Table from manual throughput to autoscale. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._migrate_table_to_autoscale_initial( - resource_group_name=resource_group_name, - account_name=account_name, - table_name=table_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _migrate_table_to_manual_throughput_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_table_to_manual_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - table_name=table_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_migrate_table_to_manual_throughput( - self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB Table from autoscale to manual throughput. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._migrate_table_to_manual_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - table_name=table_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _retrieve_continuous_backup_information_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - table_name: str, - location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(location, (IOBase, bytes)): - _content = location - else: - _json = self._serialize.body(location, "ContinuousBackupRestoreLocation") - - _request = build_retrieve_continuous_backup_information_request( - resource_group_name=resource_group_name, - account_name=account_name, - table_name=table_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - table_name: str, - location: _models.ContinuousBackupRestoreLocation, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.BackupInformation]: - """Retrieves continuous backup information for a table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :param location: The name of the continuous backup restore location. Required. - :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either BackupInformation or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - table_name: str, - location: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.BackupInformation]: - """Retrieves continuous backup information for a table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :param location: The name of the continuous backup restore location. Required. - :type location: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either BackupInformation or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - table_name: str, - location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.BackupInformation]: - """Retrieves continuous backup information for a table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :param location: The name of the continuous backup restore location. Is either a - ContinuousBackupRestoreLocation type or a IO[bytes] type. Required. - :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation or IO[bytes] - :return: An instance of AsyncLROPoller that returns either BackupInformation or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.BackupInformation] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._retrieve_continuous_backup_information_initial( - resource_group_name=resource_group_name, - account_name=account_name, - table_name=table_name, - location=location, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("BackupInformation", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.BackupInformation].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.BackupInformation]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ...operations._table_resources_operations import ( + build_create_update_table_request, + build_delete_table_request, + build_get_table_request, + build_get_table_throughput_request, + build_list_tables_request, + build_migrate_table_to_autoscale_request, + build_migrate_table_to_manual_throughput_request, + build_retrieve_continuous_backup_information_request, + build_update_table_throughput_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class TableResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`table_resources` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_tables( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> AsyncIterable["_models.TableGetResults"]: + """Lists the Tables under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either TableGetResults or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.TableGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.TableListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_tables_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("TableListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get_table( + self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any + ) -> _models.TableGetResults: + """Gets the Tables under an existing Azure Cosmos DB database account with the provided name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :return: TableGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.TableGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.TableGetResults] = kwargs.pop("cls", None) + + _request = build_get_table_request( + resource_group_name=resource_group_name, + account_name=account_name, + table_name=table_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("TableGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_update_table_initial( + self, + resource_group_name: str, + account_name: str, + table_name: str, + create_update_table_parameters: Union[_models.TableCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_table_parameters, (IOBase, bytes)): + _content = create_update_table_parameters + else: + _json = self._serialize.body(create_update_table_parameters, "TableCreateUpdateParameters") + + _request = build_create_update_table_request( + resource_group_name=resource_group_name, + account_name=account_name, + table_name=table_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_update_table( + self, + resource_group_name: str, + account_name: str, + table_name: str, + create_update_table_parameters: _models.TableCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.TableGetResults]: + """Create or update an Azure Cosmos DB Table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :param create_update_table_parameters: The parameters to provide for the current Table. + Required. + :type create_update_table_parameters: ~azure.mgmt.cosmosdb.models.TableCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either TableGetResults or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.TableGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_update_table( + self, + resource_group_name: str, + account_name: str, + table_name: str, + create_update_table_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.TableGetResults]: + """Create or update an Azure Cosmos DB Table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :param create_update_table_parameters: The parameters to provide for the current Table. + Required. + :type create_update_table_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either TableGetResults or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.TableGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_update_table( + self, + resource_group_name: str, + account_name: str, + table_name: str, + create_update_table_parameters: Union[_models.TableCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.TableGetResults]: + """Create or update an Azure Cosmos DB Table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :param create_update_table_parameters: The parameters to provide for the current Table. Is + either a TableCreateUpdateParameters type or a IO[bytes] type. Required. + :type create_update_table_parameters: ~azure.mgmt.cosmosdb.models.TableCreateUpdateParameters + or IO[bytes] + :return: An instance of AsyncLROPoller that returns either TableGetResults or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.TableGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.TableGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_update_table_initial( + resource_group_name=resource_group_name, + account_name=account_name, + table_name=table_name, + create_update_table_parameters=create_update_table_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("TableGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.TableGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.TableGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_table_initial( + self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_table_request( + resource_group_name=resource_group_name, + account_name=account_name, + table_name=table_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete_table( + self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes an existing Azure Cosmos DB Table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_table_initial( + resource_group_name=resource_group_name, + account_name=account_name, + table_name=table_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace_async + async def get_table_throughput( + self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any + ) -> _models.ThroughputSettingsGetResults: + """Gets the RUs per second of the Table under an existing Azure Cosmos DB database account with + the provided name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :return: ThroughputSettingsGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + + _request = build_get_table_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + table_name=table_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _update_table_throughput_initial( + self, + resource_group_name: str, + account_name: str, + table_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(update_throughput_parameters, (IOBase, bytes)): + _content = update_throughput_parameters + else: + _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") + + _request = build_update_table_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + table_name=table_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_update_table_throughput( + self, + resource_group_name: str, + account_name: str, + table_name: str, + update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :param update_throughput_parameters: The parameters to provide for the RUs per second of the + current Table. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update_table_throughput( + self, + resource_group_name: str, + account_name: str, + table_name: str, + update_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :param update_throughput_parameters: The parameters to provide for the RUs per second of the + current Table. Required. + :type update_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update_table_throughput( + self, + resource_group_name: str, + account_name: str, + table_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :param update_throughput_parameters: The parameters to provide for the RUs per second of the + current Table. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] type. + Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._update_table_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + table_name=table_name, + update_throughput_parameters=update_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _migrate_table_to_autoscale_initial( + self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_table_to_autoscale_request( + resource_group_name=resource_group_name, + account_name=account_name, + table_name=table_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_migrate_table_to_autoscale( + self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB Table from manual throughput to autoscale. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._migrate_table_to_autoscale_initial( + resource_group_name=resource_group_name, + account_name=account_name, + table_name=table_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _migrate_table_to_manual_throughput_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_table_to_manual_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + table_name=table_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_migrate_table_to_manual_throughput( + self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB Table from autoscale to manual throughput. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._migrate_table_to_manual_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + table_name=table_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _retrieve_continuous_backup_information_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + table_name: str, + location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(location, (IOBase, bytes)): + _content = location + else: + _json = self._serialize.body(location, "ContinuousBackupRestoreLocation") + + _request = build_retrieve_continuous_backup_information_request( + resource_group_name=resource_group_name, + account_name=account_name, + table_name=table_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + table_name: str, + location: _models.ContinuousBackupRestoreLocation, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.BackupInformation]: + """Retrieves continuous backup information for a table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :param location: The name of the continuous backup restore location. Required. + :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either BackupInformation or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + table_name: str, + location: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.BackupInformation]: + """Retrieves continuous backup information for a table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :param location: The name of the continuous backup restore location. Required. + :type location: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either BackupInformation or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + table_name: str, + location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.BackupInformation]: + """Retrieves continuous backup information for a table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :param location: The name of the continuous backup restore location. Is either a + ContinuousBackupRestoreLocation type or a IO[bytes] type. Required. + :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation or IO[bytes] + :return: An instance of AsyncLROPoller that returns either BackupInformation or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.BackupInformation] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._retrieve_continuous_backup_information_initial( + resource_group_name=resource_group_name, + account_name=account_name, + table_name=table_name, + location=location, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("BackupInformation", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.BackupInformation].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.BackupInformation]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_throughput_pool_account_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_throughput_pool_account_operations.py index 14ed4c5d19d..7044b9d5b3f 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_throughput_pool_account_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_throughput_pool_account_operations.py @@ -1,460 +1,460 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling - -from ... import models as _models -from ...operations._throughput_pool_account_operations import ( - build_create_request, - build_delete_request, - build_get_request, -) - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class ThroughputPoolAccountOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`throughput_pool_account` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def get( - self, resource_group_name: str, throughput_pool_name: str, throughput_pool_account_name: str, **kwargs: Any - ) -> _models.ThroughputPoolAccountResource: - """Retrieves the properties of an existing Azure Cosmos DB Throughput Pool. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. - :type throughput_pool_name: str - :param throughput_pool_account_name: Cosmos DB global database account in a Throughput Pool. - Required. - :type throughput_pool_account_name: str - :return: ThroughputPoolAccountResource or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ThroughputPoolAccountResource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputPoolAccountResource] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - throughput_pool_name=throughput_pool_name, - throughput_pool_account_name=throughput_pool_account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ThroughputPoolAccountResource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _create_initial( - self, - resource_group_name: str, - throughput_pool_name: str, - throughput_pool_account_name: str, - body: Union[_models.ThroughputPoolAccountResource, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _json = self._serialize.body(body, "ThroughputPoolAccountResource") - - _request = build_create_request( - resource_group_name=resource_group_name, - throughput_pool_name=throughput_pool_name, - throughput_pool_account_name=throughput_pool_account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create( - self, - resource_group_name: str, - throughput_pool_name: str, - throughput_pool_account_name: str, - body: _models.ThroughputPoolAccountResource, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputPoolAccountResource]: - """Creates or updates an Azure Cosmos DB ThroughputPool account. The "Update" method is preferred - when performing updates on an account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. - :type throughput_pool_name: str - :param throughput_pool_account_name: Cosmos DB global database account in a Throughput Pool. - Required. - :type throughput_pool_account_name: str - :param body: The parameters to provide for the current ThroughputPoolAccount. Required. - :type body: ~azure.mgmt.cosmosdb.models.ThroughputPoolAccountResource - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ThroughputPoolAccountResource or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolAccountResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create( - self, - resource_group_name: str, - throughput_pool_name: str, - throughput_pool_account_name: str, - body: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputPoolAccountResource]: - """Creates or updates an Azure Cosmos DB ThroughputPool account. The "Update" method is preferred - when performing updates on an account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. - :type throughput_pool_name: str - :param throughput_pool_account_name: Cosmos DB global database account in a Throughput Pool. - Required. - :type throughput_pool_account_name: str - :param body: The parameters to provide for the current ThroughputPoolAccount. Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ThroughputPoolAccountResource or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolAccountResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create( - self, - resource_group_name: str, - throughput_pool_name: str, - throughput_pool_account_name: str, - body: Union[_models.ThroughputPoolAccountResource, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputPoolAccountResource]: - """Creates or updates an Azure Cosmos DB ThroughputPool account. The "Update" method is preferred - when performing updates on an account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. - :type throughput_pool_name: str - :param throughput_pool_account_name: Cosmos DB global database account in a Throughput Pool. - Required. - :type throughput_pool_account_name: str - :param body: The parameters to provide for the current ThroughputPoolAccount. Is either a - ThroughputPoolAccountResource type or a IO[bytes] type. Required. - :type body: ~azure.mgmt.cosmosdb.models.ThroughputPoolAccountResource or IO[bytes] - :return: An instance of AsyncLROPoller that returns either ThroughputPoolAccountResource or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolAccountResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ThroughputPoolAccountResource] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_initial( - resource_group_name=resource_group_name, - throughput_pool_name=throughput_pool_name, - throughput_pool_account_name=throughput_pool_account_name, - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputPoolAccountResource", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, - AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs), - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputPoolAccountResource].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputPoolAccountResource]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _delete_initial( - self, resource_group_name: str, throughput_pool_name: str, throughput_pool_account_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - throughput_pool_name=throughput_pool_name, - throughput_pool_account_name=throughput_pool_account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete( - self, resource_group_name: str, throughput_pool_name: str, throughput_pool_account_name: str, **kwargs: Any - ) -> AsyncLROPoller[None]: - """Removes an existing Azure Cosmos DB database account from a throughput pool. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. - :type throughput_pool_name: str - :param throughput_pool_account_name: Cosmos DB global database account in a Throughput Pool. - Required. - :type throughput_pool_account_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_initial( - resource_group_name=resource_group_name, - throughput_pool_name=throughput_pool_name, - throughput_pool_account_name=throughput_pool_account_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ...operations._throughput_pool_account_operations import ( + build_create_request, + build_delete_request, + build_get_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class ThroughputPoolAccountOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`throughput_pool_account` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get( + self, resource_group_name: str, throughput_pool_name: str, throughput_pool_account_name: str, **kwargs: Any + ) -> _models.ThroughputPoolAccountResource: + """Retrieves the properties of an existing Azure Cosmos DB Throughput Pool. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. + :type throughput_pool_name: str + :param throughput_pool_account_name: Cosmos DB global database account in a Throughput Pool. + Required. + :type throughput_pool_account_name: str + :return: ThroughputPoolAccountResource or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ThroughputPoolAccountResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputPoolAccountResource] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + throughput_pool_name=throughput_pool_name, + throughput_pool_account_name=throughput_pool_account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ThroughputPoolAccountResource", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_initial( + self, + resource_group_name: str, + throughput_pool_name: str, + throughput_pool_account_name: str, + body: Union[_models.ThroughputPoolAccountResource, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "ThroughputPoolAccountResource") + + _request = build_create_request( + resource_group_name=resource_group_name, + throughput_pool_name=throughput_pool_name, + throughput_pool_account_name=throughput_pool_account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create( + self, + resource_group_name: str, + throughput_pool_name: str, + throughput_pool_account_name: str, + body: _models.ThroughputPoolAccountResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputPoolAccountResource]: + """Creates or updates an Azure Cosmos DB ThroughputPool account. The "Update" method is preferred + when performing updates on an account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. + :type throughput_pool_name: str + :param throughput_pool_account_name: Cosmos DB global database account in a Throughput Pool. + Required. + :type throughput_pool_account_name: str + :param body: The parameters to provide for the current ThroughputPoolAccount. Required. + :type body: ~azure.mgmt.cosmosdb.models.ThroughputPoolAccountResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ThroughputPoolAccountResource or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolAccountResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create( + self, + resource_group_name: str, + throughput_pool_name: str, + throughput_pool_account_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputPoolAccountResource]: + """Creates or updates an Azure Cosmos DB ThroughputPool account. The "Update" method is preferred + when performing updates on an account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. + :type throughput_pool_name: str + :param throughput_pool_account_name: Cosmos DB global database account in a Throughput Pool. + Required. + :type throughput_pool_account_name: str + :param body: The parameters to provide for the current ThroughputPoolAccount. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ThroughputPoolAccountResource or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolAccountResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create( + self, + resource_group_name: str, + throughput_pool_name: str, + throughput_pool_account_name: str, + body: Union[_models.ThroughputPoolAccountResource, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputPoolAccountResource]: + """Creates or updates an Azure Cosmos DB ThroughputPool account. The "Update" method is preferred + when performing updates on an account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. + :type throughput_pool_name: str + :param throughput_pool_account_name: Cosmos DB global database account in a Throughput Pool. + Required. + :type throughput_pool_account_name: str + :param body: The parameters to provide for the current ThroughputPoolAccount. Is either a + ThroughputPoolAccountResource type or a IO[bytes] type. Required. + :type body: ~azure.mgmt.cosmosdb.models.ThroughputPoolAccountResource or IO[bytes] + :return: An instance of AsyncLROPoller that returns either ThroughputPoolAccountResource or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolAccountResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ThroughputPoolAccountResource] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_initial( + resource_group_name=resource_group_name, + throughput_pool_name=throughput_pool_name, + throughput_pool_account_name=throughput_pool_account_name, + body=body, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputPoolAccountResource", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, + AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs), + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputPoolAccountResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputPoolAccountResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_initial( + self, resource_group_name: str, throughput_pool_name: str, throughput_pool_account_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + throughput_pool_name=throughput_pool_name, + throughput_pool_account_name=throughput_pool_account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete( + self, resource_group_name: str, throughput_pool_name: str, throughput_pool_account_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Removes an existing Azure Cosmos DB database account from a throughput pool. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. + :type throughput_pool_name: str + :param throughput_pool_account_name: Cosmos DB global database account in a Throughput Pool. + Required. + :type throughput_pool_account_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + throughput_pool_name=throughput_pool_name, + throughput_pool_account_name=throughput_pool_account_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_throughput_pool_accounts_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_throughput_pool_accounts_operations.py index bf4c4f117ce..952fe9da8d7 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_throughput_pool_accounts_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_throughput_pool_accounts_operations.py @@ -1,142 +1,142 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._throughput_pool_accounts_operations import build_list_request - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class ThroughputPoolAccountsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`throughput_pool_accounts` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, resource_group_name: str, throughput_pool_name: str, **kwargs: Any - ) -> AsyncIterable["_models.ThroughputPoolAccountResource"]: - """Lists all the Azure Cosmos DB accounts available under the subscription. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. - :type throughput_pool_name: str - :return: An iterator like instance of either ThroughputPoolAccountResource or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.ThroughputPoolAccountResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputPoolAccountsListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - resource_group_name=resource_group_name, - throughput_pool_name=throughput_pool_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("ThroughputPoolAccountsListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._throughput_pool_accounts_operations import build_list_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class ThroughputPoolAccountsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`throughput_pool_accounts` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, resource_group_name: str, throughput_pool_name: str, **kwargs: Any + ) -> AsyncIterable["_models.ThroughputPoolAccountResource"]: + """Lists all the Azure Cosmos DB accounts available under the subscription. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. + :type throughput_pool_name: str + :return: An iterator like instance of either ThroughputPoolAccountResource or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.ThroughputPoolAccountResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputPoolAccountsListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + resource_group_name=resource_group_name, + throughput_pool_name=throughput_pool_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ThroughputPoolAccountsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_throughput_pool_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_throughput_pool_operations.py index 1861b5a583c..6c924aad5fd 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_throughput_pool_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_throughput_pool_operations.py @@ -1,640 +1,640 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling - -from ... import models as _models -from ...operations._throughput_pool_operations import ( - build_create_or_update_request, - build_delete_request, - build_get_request, - build_update_request, -) - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class ThroughputPoolOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`throughput_pool` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def get( - self, resource_group_name: str, throughput_pool_name: str, **kwargs: Any - ) -> _models.ThroughputPoolResource: - """Retrieves the properties of an existing Azure Cosmos DB Throughput Pool. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. - :type throughput_pool_name: str - :return: ThroughputPoolResource or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ThroughputPoolResource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputPoolResource] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - throughput_pool_name=throughput_pool_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ThroughputPoolResource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _create_or_update_initial( - self, - resource_group_name: str, - throughput_pool_name: str, - body: Union[_models.ThroughputPoolResource, IO[bytes]], - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _json = self._serialize.body(body, "ThroughputPoolResource") - - _request = build_create_or_update_request( - resource_group_name=resource_group_name, - throughput_pool_name=throughput_pool_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_or_update( - self, - resource_group_name: str, - throughput_pool_name: str, - body: _models.ThroughputPoolResource, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputPoolResource]: - """Creates or updates an Azure Cosmos DB ThroughputPool account. The "Update" method is preferred - when performing updates on an account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. - :type throughput_pool_name: str - :param body: The parameters to provide for the current ThroughputPool. Required. - :type body: ~azure.mgmt.cosmosdb.models.ThroughputPoolResource - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ThroughputPoolResource or the result - of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_or_update( - self, - resource_group_name: str, - throughput_pool_name: str, - body: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputPoolResource]: - """Creates or updates an Azure Cosmos DB ThroughputPool account. The "Update" method is preferred - when performing updates on an account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. - :type throughput_pool_name: str - :param body: The parameters to provide for the current ThroughputPool. Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ThroughputPoolResource or the result - of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_or_update( - self, - resource_group_name: str, - throughput_pool_name: str, - body: Union[_models.ThroughputPoolResource, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputPoolResource]: - """Creates or updates an Azure Cosmos DB ThroughputPool account. The "Update" method is preferred - when performing updates on an account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. - :type throughput_pool_name: str - :param body: The parameters to provide for the current ThroughputPool. Is either a - ThroughputPoolResource type or a IO[bytes] type. Required. - :type body: ~azure.mgmt.cosmosdb.models.ThroughputPoolResource or IO[bytes] - :return: An instance of AsyncLROPoller that returns either ThroughputPoolResource or the result - of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ThroughputPoolResource] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_or_update_initial( - resource_group_name=resource_group_name, - throughput_pool_name=throughput_pool_name, - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputPoolResource", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, - AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs), - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputPoolResource].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputPoolResource]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _update_initial( - self, - resource_group_name: str, - throughput_pool_name: str, - body: Optional[Union[_models.ThroughputPoolUpdate, IO[bytes]]] = None, - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - if body is not None: - _json = self._serialize.body(body, "ThroughputPoolUpdate") - else: - _json = None - - _request = build_update_request( - resource_group_name=resource_group_name, - throughput_pool_name=throughput_pool_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_update( - self, - resource_group_name: str, - throughput_pool_name: str, - body: Optional[_models.ThroughputPoolUpdate] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputPoolResource]: - """Updates the properties of an existing Azure Cosmos DB Throughput Pool. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. - :type throughput_pool_name: str - :param body: The parameters to provide for the current Throughput Pool. Default value is None. - :type body: ~azure.mgmt.cosmosdb.models.ThroughputPoolUpdate - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ThroughputPoolResource or the result - of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_update( - self, - resource_group_name: str, - throughput_pool_name: str, - body: Optional[IO[bytes]] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputPoolResource]: - """Updates the properties of an existing Azure Cosmos DB Throughput Pool. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. - :type throughput_pool_name: str - :param body: The parameters to provide for the current Throughput Pool. Default value is None. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either ThroughputPoolResource or the result - of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_update( - self, - resource_group_name: str, - throughput_pool_name: str, - body: Optional[Union[_models.ThroughputPoolUpdate, IO[bytes]]] = None, - **kwargs: Any - ) -> AsyncLROPoller[_models.ThroughputPoolResource]: - """Updates the properties of an existing Azure Cosmos DB Throughput Pool. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. - :type throughput_pool_name: str - :param body: The parameters to provide for the current Throughput Pool. Is either a - ThroughputPoolUpdate type or a IO[bytes] type. Default value is None. - :type body: ~azure.mgmt.cosmosdb.models.ThroughputPoolUpdate or IO[bytes] - :return: An instance of AsyncLROPoller that returns either ThroughputPoolResource or the result - of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ThroughputPoolResource] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._update_initial( - resource_group_name=resource_group_name, - throughput_pool_name=throughput_pool_name, - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputPoolResource", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, - AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs), - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.ThroughputPoolResource].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.ThroughputPoolResource]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _delete_initial( - self, resource_group_name: str, throughput_pool_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - throughput_pool_name=throughput_pool_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete( - self, resource_group_name: str, throughput_pool_name: str, **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes an existing Azure Cosmos DB Throughput Pool. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. - :type throughput_pool_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_initial( - resource_group_name=resource_group_name, - throughput_pool_name=throughput_pool_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ...operations._throughput_pool_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_update_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class ThroughputPoolOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`throughput_pool` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get( + self, resource_group_name: str, throughput_pool_name: str, **kwargs: Any + ) -> _models.ThroughputPoolResource: + """Retrieves the properties of an existing Azure Cosmos DB Throughput Pool. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. + :type throughput_pool_name: str + :return: ThroughputPoolResource or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ThroughputPoolResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputPoolResource] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + throughput_pool_name=throughput_pool_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ThroughputPoolResource", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_or_update_initial( + self, + resource_group_name: str, + throughput_pool_name: str, + body: Union[_models.ThroughputPoolResource, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "ThroughputPoolResource") + + _request = build_create_or_update_request( + resource_group_name=resource_group_name, + throughput_pool_name=throughput_pool_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + throughput_pool_name: str, + body: _models.ThroughputPoolResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputPoolResource]: + """Creates or updates an Azure Cosmos DB ThroughputPool account. The "Update" method is preferred + when performing updates on an account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. + :type throughput_pool_name: str + :param body: The parameters to provide for the current ThroughputPool. Required. + :type body: ~azure.mgmt.cosmosdb.models.ThroughputPoolResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ThroughputPoolResource or the result + of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + throughput_pool_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputPoolResource]: + """Creates or updates an Azure Cosmos DB ThroughputPool account. The "Update" method is preferred + when performing updates on an account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. + :type throughput_pool_name: str + :param body: The parameters to provide for the current ThroughputPool. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ThroughputPoolResource or the result + of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + throughput_pool_name: str, + body: Union[_models.ThroughputPoolResource, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputPoolResource]: + """Creates or updates an Azure Cosmos DB ThroughputPool account. The "Update" method is preferred + when performing updates on an account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. + :type throughput_pool_name: str + :param body: The parameters to provide for the current ThroughputPool. Is either a + ThroughputPoolResource type or a IO[bytes] type. Required. + :type body: ~azure.mgmt.cosmosdb.models.ThroughputPoolResource or IO[bytes] + :return: An instance of AsyncLROPoller that returns either ThroughputPoolResource or the result + of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ThroughputPoolResource] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + throughput_pool_name=throughput_pool_name, + body=body, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputPoolResource", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, + AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs), + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputPoolResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputPoolResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _update_initial( + self, + resource_group_name: str, + throughput_pool_name: str, + body: Optional[Union[_models.ThroughputPoolUpdate, IO[bytes]]] = None, + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + if body is not None: + _json = self._serialize.body(body, "ThroughputPoolUpdate") + else: + _json = None + + _request = build_update_request( + resource_group_name=resource_group_name, + throughput_pool_name=throughput_pool_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_update( + self, + resource_group_name: str, + throughput_pool_name: str, + body: Optional[_models.ThroughputPoolUpdate] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputPoolResource]: + """Updates the properties of an existing Azure Cosmos DB Throughput Pool. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. + :type throughput_pool_name: str + :param body: The parameters to provide for the current Throughput Pool. Default value is None. + :type body: ~azure.mgmt.cosmosdb.models.ThroughputPoolUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ThroughputPoolResource or the result + of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update( + self, + resource_group_name: str, + throughput_pool_name: str, + body: Optional[IO[bytes]] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputPoolResource]: + """Updates the properties of an existing Azure Cosmos DB Throughput Pool. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. + :type throughput_pool_name: str + :param body: The parameters to provide for the current Throughput Pool. Default value is None. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ThroughputPoolResource or the result + of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update( + self, + resource_group_name: str, + throughput_pool_name: str, + body: Optional[Union[_models.ThroughputPoolUpdate, IO[bytes]]] = None, + **kwargs: Any + ) -> AsyncLROPoller[_models.ThroughputPoolResource]: + """Updates the properties of an existing Azure Cosmos DB Throughput Pool. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. + :type throughput_pool_name: str + :param body: The parameters to provide for the current Throughput Pool. Is either a + ThroughputPoolUpdate type or a IO[bytes] type. Default value is None. + :type body: ~azure.mgmt.cosmosdb.models.ThroughputPoolUpdate or IO[bytes] + :return: An instance of AsyncLROPoller that returns either ThroughputPoolResource or the result + of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ThroughputPoolResource] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._update_initial( + resource_group_name=resource_group_name, + throughput_pool_name=throughput_pool_name, + body=body, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputPoolResource", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, + AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs), + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ThroughputPoolResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ThroughputPoolResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_initial( + self, resource_group_name: str, throughput_pool_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + throughput_pool_name=throughput_pool_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete( + self, resource_group_name: str, throughput_pool_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes an existing Azure Cosmos DB Throughput Pool. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. + :type throughput_pool_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + throughput_pool_name=throughput_pool_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_throughput_pools_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_throughput_pools_operations.py index c03eaa1f97f..2e2477813bb 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_throughput_pools_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/aio/operations/_throughput_pools_operations.py @@ -1,216 +1,216 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ...operations._throughput_pools_operations import build_list_by_resource_group_request, build_list_request - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class ThroughputPoolsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s - :attr:`throughput_pools` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list(self, **kwargs: Any) -> AsyncIterable["_models.ThroughputPoolResource"]: - """Lists all the Azure Cosmos DB Throughput Pools available under the subscription. - - :return: An iterator like instance of either ThroughputPoolResource or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputPoolsListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("ThroughputPoolsListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - def list_by_resource_group( - self, resource_group_name: str, **kwargs: Any - ) -> AsyncIterable["_models.ThroughputPoolResource"]: - """List all the ThroughputPools in a given resource group. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :return: An iterator like instance of either ThroughputPoolResource or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputPoolsListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_by_resource_group_request( - resource_group_name=resource_group_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("ThroughputPoolsListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._throughput_pools_operations import build_list_by_resource_group_request, build_list_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class ThroughputPoolsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s + :attr:`throughput_pools` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.ThroughputPoolResource"]: + """Lists all the Azure Cosmos DB Throughput Pools available under the subscription. + + :return: An iterator like instance of either ThroughputPoolResource or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputPoolsListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ThroughputPoolsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_resource_group( + self, resource_group_name: str, **kwargs: Any + ) -> AsyncIterable["_models.ThroughputPoolResource"]: + """List all the ThroughputPools in a given resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :return: An iterator like instance of either ThroughputPoolResource or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputPoolsListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ThroughputPoolsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/models/__init__.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/models/__init__.py index 8f31970b06b..e41e894306b 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/models/__init__.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/models/__init__.py @@ -1,827 +1,827 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._models_py3 import ARMProxyResource -from ._models_py3 import ARMResourceProperties -from ._models_py3 import AccessRule -from ._models_py3 import AccessRuleProperties -from ._models_py3 import AccessRulePropertiesSubscriptionsItem -from ._models_py3 import AccountKeyMetadata -from ._models_py3 import AnalyticalStorageConfiguration -from ._models_py3 import ApiProperties -from ._models_py3 import AuthenticationMethodLdapProperties -from ._models_py3 import AutoUpgradePolicyResource -from ._models_py3 import AutoscaleSettings -from ._models_py3 import AutoscaleSettingsResource -from ._models_py3 import AzureBlobDataTransferDataSourceSink -from ._models_py3 import BackupInformation -from ._models_py3 import BackupPolicy -from ._models_py3 import BackupPolicyMigrationState -from ._models_py3 import BackupResource -from ._models_py3 import BackupSchedule -from ._models_py3 import BaseCosmosDataTransferDataSourceSink -from ._models_py3 import Capability -from ._models_py3 import Capacity -from ._models_py3 import CapacityModeChangeTransitionState -from ._models_py3 import CassandraClusterDataCenterNodeItem -from ._models_py3 import CassandraClusterPublicStatus -from ._models_py3 import CassandraClusterPublicStatusDataCentersItem -from ._models_py3 import CassandraError -from ._models_py3 import CassandraKeyspaceCreateUpdateParameters -from ._models_py3 import CassandraKeyspaceGetPropertiesOptions -from ._models_py3 import CassandraKeyspaceGetPropertiesResource -from ._models_py3 import CassandraKeyspaceGetResults -from ._models_py3 import CassandraKeyspaceListResult -from ._models_py3 import CassandraKeyspaceResource -from ._models_py3 import CassandraPartitionKey -from ._models_py3 import CassandraSchema -from ._models_py3 import CassandraTableCreateUpdateParameters -from ._models_py3 import CassandraTableGetPropertiesOptions -from ._models_py3 import CassandraTableGetPropertiesResource -from ._models_py3 import CassandraTableGetResults -from ._models_py3 import CassandraTableListResult -from ._models_py3 import CassandraTableResource -from ._models_py3 import CassandraViewCreateUpdateParameters -from ._models_py3 import CassandraViewGetPropertiesOptions -from ._models_py3 import CassandraViewGetPropertiesResource -from ._models_py3 import CassandraViewGetResults -from ._models_py3 import CassandraViewListResult -from ._models_py3 import CassandraViewResource -from ._models_py3 import Certificate -from ._models_py3 import ChaosFaultListResponse -from ._models_py3 import ChaosFaultResource -from ._models_py3 import ClientEncryptionIncludedPath -from ._models_py3 import ClientEncryptionKeyCreateUpdateParameters -from ._models_py3 import ClientEncryptionKeyGetPropertiesResource -from ._models_py3 import ClientEncryptionKeyGetResults -from ._models_py3 import ClientEncryptionKeyResource -from ._models_py3 import ClientEncryptionKeysListResult -from ._models_py3 import ClientEncryptionPolicy -from ._models_py3 import ClusterKey -from ._models_py3 import ClusterResource -from ._models_py3 import ClusterResourceProperties -from ._models_py3 import Column -from ._models_py3 import CommandOutput -from ._models_py3 import CommandPostBody -from ._models_py3 import CommandPublicResource -from ._models_py3 import CompositePath -from ._models_py3 import ComputedProperty -from ._models_py3 import ConflictResolutionPolicy -from ._models_py3 import ConnectionError -from ._models_py3 import ConsistencyPolicy -from ._models_py3 import ContainerPartitionKey -from ._models_py3 import ContinuousBackupInformation -from ._models_py3 import ContinuousBackupRestoreLocation -from ._models_py3 import ContinuousModeBackupPolicy -from ._models_py3 import ContinuousModeProperties -from ._models_py3 import CorsPolicy -from ._models_py3 import CosmosCassandraDataTransferDataSourceSink -from ._models_py3 import CosmosMongoDataTransferDataSourceSink -from ._models_py3 import CosmosMongoVCoreDataTransferDataSourceSink -from ._models_py3 import CosmosSqlDataTransferDataSourceSink -from ._models_py3 import CreateJobRequest -from ._models_py3 import CreateUpdateOptions -from ._models_py3 import DataCenterResource -from ._models_py3 import DataCenterResourceProperties -from ._models_py3 import DataTransferDataSourceSink -from ._models_py3 import DataTransferJobFeedResults -from ._models_py3 import DataTransferJobGetResults -from ._models_py3 import DataTransferJobProperties -from ._models_py3 import DataTransferRegionalServiceResource -from ._models_py3 import DataTransferServiceResource -from ._models_py3 import DataTransferServiceResourceCreateUpdateProperties -from ._models_py3 import DataTransferServiceResourceProperties -from ._models_py3 import DatabaseAccountConnectionString -from ._models_py3 import DatabaseAccountCreateUpdateParameters -from ._models_py3 import DatabaseAccountGetResults -from ._models_py3 import DatabaseAccountKeysMetadata -from ._models_py3 import DatabaseAccountListConnectionStringsResult -from ._models_py3 import DatabaseAccountListKeysResult -from ._models_py3 import DatabaseAccountListReadOnlyKeysResult -from ._models_py3 import DatabaseAccountRegenerateKeyParameters -from ._models_py3 import DatabaseAccountUpdateParameters -from ._models_py3 import DatabaseAccountsListResult -from ._models_py3 import DatabaseRestoreResource -from ._models_py3 import DiagnosticLogSettings -from ._models_py3 import ErrorAdditionalInfo -from ._models_py3 import ErrorDetail -from ._models_py3 import ErrorResponse -from ._models_py3 import ErrorResponseAutoGenerated -from ._models_py3 import ExcludedPath -from ._models_py3 import ExtendedResourceProperties -from ._models_py3 import FailoverPolicies -from ._models_py3 import FailoverPolicy -from ._models_py3 import GraphAPIComputeRegionalServiceResource -from ._models_py3 import GraphAPIComputeServiceResource -from ._models_py3 import GraphAPIComputeServiceResourceCreateUpdateProperties -from ._models_py3 import GraphAPIComputeServiceResourceProperties -from ._models_py3 import GraphResource -from ._models_py3 import GraphResourceCreateUpdateParameters -from ._models_py3 import GraphResourceGetPropertiesOptions -from ._models_py3 import GraphResourceGetPropertiesResource -from ._models_py3 import GraphResourceGetResults -from ._models_py3 import GraphResourcesListResult -from ._models_py3 import GremlinDatabaseCreateUpdateParameters -from ._models_py3 import GremlinDatabaseGetPropertiesOptions -from ._models_py3 import GremlinDatabaseGetPropertiesResource -from ._models_py3 import GremlinDatabaseGetResults -from ._models_py3 import GremlinDatabaseListResult -from ._models_py3 import GremlinDatabaseResource -from ._models_py3 import GremlinDatabaseRestoreResource -from ._models_py3 import GremlinGraphCreateUpdateParameters -from ._models_py3 import GremlinGraphGetPropertiesOptions -from ._models_py3 import GremlinGraphGetPropertiesResource -from ._models_py3 import GremlinGraphGetResults -from ._models_py3 import GremlinGraphListResult -from ._models_py3 import GremlinGraphResource -from ._models_py3 import IncludedPath -from ._models_py3 import Indexes -from ._models_py3 import IndexingPolicy -from ._models_py3 import IpAddressOrRange -from ._models_py3 import KeyWrapMetadata -from ._models_py3 import ListBackups -from ._models_py3 import ListClusters -from ._models_py3 import ListCommands -from ._models_py3 import ListDataCenters -from ._models_py3 import Location -from ._models_py3 import LocationGetResult -from ._models_py3 import LocationListResult -from ._models_py3 import LocationProperties -from ._models_py3 import ManagedCassandraARMResourceProperties -from ._models_py3 import ManagedCassandraManagedServiceIdentity -from ._models_py3 import ManagedCassandraReaperStatus -from ._models_py3 import ManagedServiceIdentity -from ._models_py3 import ManagedServiceIdentityUserAssignedIdentity -from ._models_py3 import MaterializedViewDefinition -from ._models_py3 import MaterializedViewsBuilderRegionalServiceResource -from ._models_py3 import MaterializedViewsBuilderServiceResource -from ._models_py3 import MaterializedViewsBuilderServiceResourceCreateUpdateProperties -from ._models_py3 import MaterializedViewsBuilderServiceResourceProperties -from ._models_py3 import MergeParameters -from ._models_py3 import Metric -from ._models_py3 import MetricAvailability -from ._models_py3 import MetricDefinition -from ._models_py3 import MetricDefinitionsListResult -from ._models_py3 import MetricListResult -from ._models_py3 import MetricName -from ._models_py3 import MetricValue -from ._models_py3 import MongoDBCollectionCreateUpdateParameters -from ._models_py3 import MongoDBCollectionGetPropertiesOptions -from ._models_py3 import MongoDBCollectionGetPropertiesResource -from ._models_py3 import MongoDBCollectionGetResults -from ._models_py3 import MongoDBCollectionListResult -from ._models_py3 import MongoDBCollectionResource -from ._models_py3 import MongoDBDatabaseCreateUpdateParameters -from ._models_py3 import MongoDBDatabaseGetPropertiesOptions -from ._models_py3 import MongoDBDatabaseGetPropertiesResource -from ._models_py3 import MongoDBDatabaseGetResults -from ._models_py3 import MongoDBDatabaseListResult -from ._models_py3 import MongoDBDatabaseResource -from ._models_py3 import MongoIndex -from ._models_py3 import MongoIndexKeys -from ._models_py3 import MongoIndexOptions -from ._models_py3 import MongoRoleDefinitionCreateUpdateParameters -from ._models_py3 import MongoRoleDefinitionGetResults -from ._models_py3 import MongoRoleDefinitionListResult -from ._models_py3 import MongoUserDefinitionCreateUpdateParameters -from ._models_py3 import MongoUserDefinitionGetResults -from ._models_py3 import MongoUserDefinitionListResult -from ._models_py3 import NetworkSecurityPerimeter -from ._models_py3 import NetworkSecurityPerimeterConfiguration -from ._models_py3 import NetworkSecurityPerimeterConfigurationListResult -from ._models_py3 import NetworkSecurityPerimeterConfigurationProperties -from ._models_py3 import NetworkSecurityProfile -from ._models_py3 import NotebookWorkspace -from ._models_py3 import NotebookWorkspaceConnectionInfoResult -from ._models_py3 import NotebookWorkspaceCreateUpdateParameters -from ._models_py3 import NotebookWorkspaceListResult -from ._models_py3 import Operation -from ._models_py3 import OperationDisplay -from ._models_py3 import OperationListResult -from ._models_py3 import OptionsResource -from ._models_py3 import PartitionMetric -from ._models_py3 import PartitionMetricListResult -from ._models_py3 import PartitionUsage -from ._models_py3 import PartitionUsagesResult -from ._models_py3 import PercentileMetric -from ._models_py3 import PercentileMetricListResult -from ._models_py3 import PercentileMetricValue -from ._models_py3 import PeriodicModeBackupPolicy -from ._models_py3 import PeriodicModeProperties -from ._models_py3 import Permission -from ._models_py3 import PhysicalPartitionId -from ._models_py3 import PhysicalPartitionStorageInfo -from ._models_py3 import PhysicalPartitionStorageInfoCollection -from ._models_py3 import PhysicalPartitionThroughputInfoProperties -from ._models_py3 import PhysicalPartitionThroughputInfoResource -from ._models_py3 import PhysicalPartitionThroughputInfoResult -from ._models_py3 import PhysicalPartitionThroughputInfoResultPropertiesResource -from ._models_py3 import PrivateEndpointConnection -from ._models_py3 import PrivateEndpointConnectionListResult -from ._models_py3 import PrivateEndpointProperty -from ._models_py3 import PrivateLinkResource -from ._models_py3 import PrivateLinkResourceListResult -from ._models_py3 import PrivateLinkServiceConnectionStateProperty -from ._models_py3 import Privilege -from ._models_py3 import PrivilegeResource -from ._models_py3 import ProvisioningIssue -from ._models_py3 import ProvisioningIssueProperties -from ._models_py3 import ProxyResource -from ._models_py3 import RedistributeThroughputParameters -from ._models_py3 import RedistributeThroughputPropertiesResource -from ._models_py3 import RegionForOnlineOffline -from ._models_py3 import RegionalServiceResource -from ._models_py3 import Resource -from ._models_py3 import ResourceAssociation -from ._models_py3 import ResourceRestoreParameters -from ._models_py3 import RestorableDatabaseAccountGetResult -from ._models_py3 import RestorableDatabaseAccountsListResult -from ._models_py3 import RestorableGremlinDatabaseGetResult -from ._models_py3 import RestorableGremlinDatabasePropertiesResource -from ._models_py3 import RestorableGremlinDatabasesListResult -from ._models_py3 import RestorableGremlinGraphGetResult -from ._models_py3 import RestorableGremlinGraphPropertiesResource -from ._models_py3 import RestorableGremlinGraphsListResult -from ._models_py3 import RestorableGremlinResourcesGetResult -from ._models_py3 import RestorableGremlinResourcesListResult -from ._models_py3 import RestorableLocationResource -from ._models_py3 import RestorableMongodbCollectionGetResult -from ._models_py3 import RestorableMongodbCollectionPropertiesResource -from ._models_py3 import RestorableMongodbCollectionsListResult -from ._models_py3 import RestorableMongodbDatabaseGetResult -from ._models_py3 import RestorableMongodbDatabasePropertiesResource -from ._models_py3 import RestorableMongodbDatabasesListResult -from ._models_py3 import RestorableMongodbResourcesGetResult -from ._models_py3 import RestorableMongodbResourcesListResult -from ._models_py3 import RestorableSqlContainerGetResult -from ._models_py3 import RestorableSqlContainerPropertiesResource -from ._models_py3 import RestorableSqlContainerPropertiesResourceContainer -from ._models_py3 import RestorableSqlContainersListResult -from ._models_py3 import RestorableSqlDatabaseGetResult -from ._models_py3 import RestorableSqlDatabasePropertiesResource -from ._models_py3 import RestorableSqlDatabasePropertiesResourceDatabase -from ._models_py3 import RestorableSqlDatabasesListResult -from ._models_py3 import RestorableSqlResourcesGetResult -from ._models_py3 import RestorableSqlResourcesListResult -from ._models_py3 import RestorableTableGetResult -from ._models_py3 import RestorableTablePropertiesResource -from ._models_py3 import RestorableTableResourcesGetResult -from ._models_py3 import RestorableTableResourcesListResult -from ._models_py3 import RestorableTablesListResult -from ._models_py3 import RestoreParameters -from ._models_py3 import RestoreParametersBase -from ._models_py3 import RetrieveThroughputParameters -from ._models_py3 import RetrieveThroughputPropertiesResource -from ._models_py3 import Role -from ._models_py3 import SeedNode -from ._models_py3 import ServiceResource -from ._models_py3 import ServiceResourceCreateUpdateParameters -from ._models_py3 import ServiceResourceCreateUpdateProperties -from ._models_py3 import ServiceResourceListResult -from ._models_py3 import ServiceResourceProperties -from ._models_py3 import SpatialSpec -from ._models_py3 import SqlContainerCreateUpdateParameters -from ._models_py3 import SqlContainerGetPropertiesOptions -from ._models_py3 import SqlContainerGetPropertiesResource -from ._models_py3 import SqlContainerGetResults -from ._models_py3 import SqlContainerListResult -from ._models_py3 import SqlContainerResource -from ._models_py3 import SqlDatabaseCreateUpdateParameters -from ._models_py3 import SqlDatabaseGetPropertiesOptions -from ._models_py3 import SqlDatabaseGetPropertiesResource -from ._models_py3 import SqlDatabaseGetResults -from ._models_py3 import SqlDatabaseListResult -from ._models_py3 import SqlDatabaseResource -from ._models_py3 import SqlDedicatedGatewayRegionalServiceResource -from ._models_py3 import SqlDedicatedGatewayServiceResource -from ._models_py3 import SqlDedicatedGatewayServiceResourceCreateUpdateProperties -from ._models_py3 import SqlDedicatedGatewayServiceResourceProperties -from ._models_py3 import SqlRoleAssignmentCreateUpdateParameters -from ._models_py3 import SqlRoleAssignmentGetResults -from ._models_py3 import SqlRoleAssignmentListResult -from ._models_py3 import SqlRoleDefinitionCreateUpdateParameters -from ._models_py3 import SqlRoleDefinitionGetResults -from ._models_py3 import SqlRoleDefinitionListResult -from ._models_py3 import SqlStoredProcedureCreateUpdateParameters -from ._models_py3 import SqlStoredProcedureGetPropertiesResource -from ._models_py3 import SqlStoredProcedureGetResults -from ._models_py3 import SqlStoredProcedureListResult -from ._models_py3 import SqlStoredProcedureResource -from ._models_py3 import SqlTriggerCreateUpdateParameters -from ._models_py3 import SqlTriggerGetPropertiesResource -from ._models_py3 import SqlTriggerGetResults -from ._models_py3 import SqlTriggerListResult -from ._models_py3 import SqlTriggerResource -from ._models_py3 import SqlUserDefinedFunctionCreateUpdateParameters -from ._models_py3 import SqlUserDefinedFunctionGetPropertiesResource -from ._models_py3 import SqlUserDefinedFunctionGetResults -from ._models_py3 import SqlUserDefinedFunctionListResult -from ._models_py3 import SqlUserDefinedFunctionResource -from ._models_py3 import SystemData -from ._models_py3 import TableCreateUpdateParameters -from ._models_py3 import TableGetPropertiesOptions -from ._models_py3 import TableGetPropertiesResource -from ._models_py3 import TableGetResults -from ._models_py3 import TableListResult -from ._models_py3 import TableResource -from ._models_py3 import ThroughputPolicyResource -from ._models_py3 import ThroughputPoolAccountCreateParameters -from ._models_py3 import ThroughputPoolAccountResource -from ._models_py3 import ThroughputPoolAccountsListResult -from ._models_py3 import ThroughputPoolResource -from ._models_py3 import ThroughputPoolUpdate -from ._models_py3 import ThroughputPoolsListResult -from ._models_py3 import ThroughputSettingsGetPropertiesResource -from ._models_py3 import ThroughputSettingsGetResults -from ._models_py3 import ThroughputSettingsResource -from ._models_py3 import ThroughputSettingsUpdateParameters -from ._models_py3 import TrackedResource -from ._models_py3 import UniqueKey -from ._models_py3 import UniqueKeyPolicy -from ._models_py3 import Usage -from ._models_py3 import UsagesResult -from ._models_py3 import VirtualNetworkRule - -from ._cosmos_db_management_client_enums import AccessRuleDirection -from ._cosmos_db_management_client_enums import AnalyticalStorageSchemaType -from ._cosmos_db_management_client_enums import ApiType -from ._cosmos_db_management_client_enums import AuthenticationMethod -from ._cosmos_db_management_client_enums import AutoReplicate -from ._cosmos_db_management_client_enums import AzureConnectionType -from ._cosmos_db_management_client_enums import BackupPolicyMigrationStatus -from ._cosmos_db_management_client_enums import BackupPolicyType -from ._cosmos_db_management_client_enums import BackupState -from ._cosmos_db_management_client_enums import BackupStorageRedundancy -from ._cosmos_db_management_client_enums import CapacityMode -from ._cosmos_db_management_client_enums import CapacityModeTransitionStatus -from ._cosmos_db_management_client_enums import ClusterType -from ._cosmos_db_management_client_enums import CommandStatus -from ._cosmos_db_management_client_enums import CompositePathSortOrder -from ._cosmos_db_management_client_enums import ConflictResolutionMode -from ._cosmos_db_management_client_enums import ConnectionState -from ._cosmos_db_management_client_enums import ConnectorOffer -from ._cosmos_db_management_client_enums import ContinuousTier -from ._cosmos_db_management_client_enums import CreateMode -from ._cosmos_db_management_client_enums import CreatedByType -from ._cosmos_db_management_client_enums import DataTransferComponent -from ._cosmos_db_management_client_enums import DataTransferJobMode -from ._cosmos_db_management_client_enums import DataType -from ._cosmos_db_management_client_enums import DatabaseAccountKind -from ._cosmos_db_management_client_enums import DedicatedGatewayType -from ._cosmos_db_management_client_enums import DefaultConsistencyLevel -from ._cosmos_db_management_client_enums import DefaultPriorityLevel -from ._cosmos_db_management_client_enums import EnableFullTextQuery -from ._cosmos_db_management_client_enums import IndexKind -from ._cosmos_db_management_client_enums import IndexingMode -from ._cosmos_db_management_client_enums import IssueType -from ._cosmos_db_management_client_enums import KeyKind -from ._cosmos_db_management_client_enums import Kind -from ._cosmos_db_management_client_enums import ManagedCassandraProvisioningState -from ._cosmos_db_management_client_enums import ManagedCassandraResourceIdentityType -from ._cosmos_db_management_client_enums import MinimalTlsVersion -from ._cosmos_db_management_client_enums import MongoRoleDefinitionType -from ._cosmos_db_management_client_enums import NetworkAclBypass -from ._cosmos_db_management_client_enums import NetworkSecurityPerimeterConfigurationProvisioningState -from ._cosmos_db_management_client_enums import NodeState -from ._cosmos_db_management_client_enums import NodeStatus -from ._cosmos_db_management_client_enums import NotebookWorkspaceName -from ._cosmos_db_management_client_enums import OperationType -from ._cosmos_db_management_client_enums import PartitionKind -from ._cosmos_db_management_client_enums import PrimaryAggregationType -from ._cosmos_db_management_client_enums import PublicNetworkAccess -from ._cosmos_db_management_client_enums import ResourceAssociationAccessMode -from ._cosmos_db_management_client_enums import ResourceIdentityType -from ._cosmos_db_management_client_enums import RestoreMode -from ._cosmos_db_management_client_enums import RoleDefinitionType -from ._cosmos_db_management_client_enums import ScheduledEventStrategy -from ._cosmos_db_management_client_enums import ServerVersion -from ._cosmos_db_management_client_enums import ServiceSize -from ._cosmos_db_management_client_enums import ServiceStatus -from ._cosmos_db_management_client_enums import ServiceType -from ._cosmos_db_management_client_enums import Severity -from ._cosmos_db_management_client_enums import SpatialType -from ._cosmos_db_management_client_enums import Status -from ._cosmos_db_management_client_enums import SupportedActions -from ._cosmos_db_management_client_enums import ThroughputPolicyType -from ._cosmos_db_management_client_enums import TriggerOperation -from ._cosmos_db_management_client_enums import TriggerType -from ._cosmos_db_management_client_enums import Type -from ._cosmos_db_management_client_enums import UnitType -from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "ARMProxyResource", - "ARMResourceProperties", - "AccessRule", - "AccessRuleProperties", - "AccessRulePropertiesSubscriptionsItem", - "AccountKeyMetadata", - "AnalyticalStorageConfiguration", - "ApiProperties", - "AuthenticationMethodLdapProperties", - "AutoUpgradePolicyResource", - "AutoscaleSettings", - "AutoscaleSettingsResource", - "AzureBlobDataTransferDataSourceSink", - "BackupInformation", - "BackupPolicy", - "BackupPolicyMigrationState", - "BackupResource", - "BackupSchedule", - "BaseCosmosDataTransferDataSourceSink", - "Capability", - "Capacity", - "CapacityModeChangeTransitionState", - "CassandraClusterDataCenterNodeItem", - "CassandraClusterPublicStatus", - "CassandraClusterPublicStatusDataCentersItem", - "CassandraError", - "CassandraKeyspaceCreateUpdateParameters", - "CassandraKeyspaceGetPropertiesOptions", - "CassandraKeyspaceGetPropertiesResource", - "CassandraKeyspaceGetResults", - "CassandraKeyspaceListResult", - "CassandraKeyspaceResource", - "CassandraPartitionKey", - "CassandraSchema", - "CassandraTableCreateUpdateParameters", - "CassandraTableGetPropertiesOptions", - "CassandraTableGetPropertiesResource", - "CassandraTableGetResults", - "CassandraTableListResult", - "CassandraTableResource", - "CassandraViewCreateUpdateParameters", - "CassandraViewGetPropertiesOptions", - "CassandraViewGetPropertiesResource", - "CassandraViewGetResults", - "CassandraViewListResult", - "CassandraViewResource", - "Certificate", - "ChaosFaultListResponse", - "ChaosFaultResource", - "ClientEncryptionIncludedPath", - "ClientEncryptionKeyCreateUpdateParameters", - "ClientEncryptionKeyGetPropertiesResource", - "ClientEncryptionKeyGetResults", - "ClientEncryptionKeyResource", - "ClientEncryptionKeysListResult", - "ClientEncryptionPolicy", - "ClusterKey", - "ClusterResource", - "ClusterResourceProperties", - "Column", - "CommandOutput", - "CommandPostBody", - "CommandPublicResource", - "CompositePath", - "ComputedProperty", - "ConflictResolutionPolicy", - "ConnectionError", - "ConsistencyPolicy", - "ContainerPartitionKey", - "ContinuousBackupInformation", - "ContinuousBackupRestoreLocation", - "ContinuousModeBackupPolicy", - "ContinuousModeProperties", - "CorsPolicy", - "CosmosCassandraDataTransferDataSourceSink", - "CosmosMongoDataTransferDataSourceSink", - "CosmosMongoVCoreDataTransferDataSourceSink", - "CosmosSqlDataTransferDataSourceSink", - "CreateJobRequest", - "CreateUpdateOptions", - "DataCenterResource", - "DataCenterResourceProperties", - "DataTransferDataSourceSink", - "DataTransferJobFeedResults", - "DataTransferJobGetResults", - "DataTransferJobProperties", - "DataTransferRegionalServiceResource", - "DataTransferServiceResource", - "DataTransferServiceResourceCreateUpdateProperties", - "DataTransferServiceResourceProperties", - "DatabaseAccountConnectionString", - "DatabaseAccountCreateUpdateParameters", - "DatabaseAccountGetResults", - "DatabaseAccountKeysMetadata", - "DatabaseAccountListConnectionStringsResult", - "DatabaseAccountListKeysResult", - "DatabaseAccountListReadOnlyKeysResult", - "DatabaseAccountRegenerateKeyParameters", - "DatabaseAccountUpdateParameters", - "DatabaseAccountsListResult", - "DatabaseRestoreResource", - "DiagnosticLogSettings", - "ErrorAdditionalInfo", - "ErrorDetail", - "ErrorResponse", - "ErrorResponseAutoGenerated", - "ExcludedPath", - "ExtendedResourceProperties", - "FailoverPolicies", - "FailoverPolicy", - "GraphAPIComputeRegionalServiceResource", - "GraphAPIComputeServiceResource", - "GraphAPIComputeServiceResourceCreateUpdateProperties", - "GraphAPIComputeServiceResourceProperties", - "GraphResource", - "GraphResourceCreateUpdateParameters", - "GraphResourceGetPropertiesOptions", - "GraphResourceGetPropertiesResource", - "GraphResourceGetResults", - "GraphResourcesListResult", - "GremlinDatabaseCreateUpdateParameters", - "GremlinDatabaseGetPropertiesOptions", - "GremlinDatabaseGetPropertiesResource", - "GremlinDatabaseGetResults", - "GremlinDatabaseListResult", - "GremlinDatabaseResource", - "GremlinDatabaseRestoreResource", - "GremlinGraphCreateUpdateParameters", - "GremlinGraphGetPropertiesOptions", - "GremlinGraphGetPropertiesResource", - "GremlinGraphGetResults", - "GremlinGraphListResult", - "GremlinGraphResource", - "IncludedPath", - "Indexes", - "IndexingPolicy", - "IpAddressOrRange", - "KeyWrapMetadata", - "ListBackups", - "ListClusters", - "ListCommands", - "ListDataCenters", - "Location", - "LocationGetResult", - "LocationListResult", - "LocationProperties", - "ManagedCassandraARMResourceProperties", - "ManagedCassandraManagedServiceIdentity", - "ManagedCassandraReaperStatus", - "ManagedServiceIdentity", - "ManagedServiceIdentityUserAssignedIdentity", - "MaterializedViewDefinition", - "MaterializedViewsBuilderRegionalServiceResource", - "MaterializedViewsBuilderServiceResource", - "MaterializedViewsBuilderServiceResourceCreateUpdateProperties", - "MaterializedViewsBuilderServiceResourceProperties", - "MergeParameters", - "Metric", - "MetricAvailability", - "MetricDefinition", - "MetricDefinitionsListResult", - "MetricListResult", - "MetricName", - "MetricValue", - "MongoDBCollectionCreateUpdateParameters", - "MongoDBCollectionGetPropertiesOptions", - "MongoDBCollectionGetPropertiesResource", - "MongoDBCollectionGetResults", - "MongoDBCollectionListResult", - "MongoDBCollectionResource", - "MongoDBDatabaseCreateUpdateParameters", - "MongoDBDatabaseGetPropertiesOptions", - "MongoDBDatabaseGetPropertiesResource", - "MongoDBDatabaseGetResults", - "MongoDBDatabaseListResult", - "MongoDBDatabaseResource", - "MongoIndex", - "MongoIndexKeys", - "MongoIndexOptions", - "MongoRoleDefinitionCreateUpdateParameters", - "MongoRoleDefinitionGetResults", - "MongoRoleDefinitionListResult", - "MongoUserDefinitionCreateUpdateParameters", - "MongoUserDefinitionGetResults", - "MongoUserDefinitionListResult", - "NetworkSecurityPerimeter", - "NetworkSecurityPerimeterConfiguration", - "NetworkSecurityPerimeterConfigurationListResult", - "NetworkSecurityPerimeterConfigurationProperties", - "NetworkSecurityProfile", - "NotebookWorkspace", - "NotebookWorkspaceConnectionInfoResult", - "NotebookWorkspaceCreateUpdateParameters", - "NotebookWorkspaceListResult", - "Operation", - "OperationDisplay", - "OperationListResult", - "OptionsResource", - "PartitionMetric", - "PartitionMetricListResult", - "PartitionUsage", - "PartitionUsagesResult", - "PercentileMetric", - "PercentileMetricListResult", - "PercentileMetricValue", - "PeriodicModeBackupPolicy", - "PeriodicModeProperties", - "Permission", - "PhysicalPartitionId", - "PhysicalPartitionStorageInfo", - "PhysicalPartitionStorageInfoCollection", - "PhysicalPartitionThroughputInfoProperties", - "PhysicalPartitionThroughputInfoResource", - "PhysicalPartitionThroughputInfoResult", - "PhysicalPartitionThroughputInfoResultPropertiesResource", - "PrivateEndpointConnection", - "PrivateEndpointConnectionListResult", - "PrivateEndpointProperty", - "PrivateLinkResource", - "PrivateLinkResourceListResult", - "PrivateLinkServiceConnectionStateProperty", - "Privilege", - "PrivilegeResource", - "ProvisioningIssue", - "ProvisioningIssueProperties", - "ProxyResource", - "RedistributeThroughputParameters", - "RedistributeThroughputPropertiesResource", - "RegionForOnlineOffline", - "RegionalServiceResource", - "Resource", - "ResourceAssociation", - "ResourceRestoreParameters", - "RestorableDatabaseAccountGetResult", - "RestorableDatabaseAccountsListResult", - "RestorableGremlinDatabaseGetResult", - "RestorableGremlinDatabasePropertiesResource", - "RestorableGremlinDatabasesListResult", - "RestorableGremlinGraphGetResult", - "RestorableGremlinGraphPropertiesResource", - "RestorableGremlinGraphsListResult", - "RestorableGremlinResourcesGetResult", - "RestorableGremlinResourcesListResult", - "RestorableLocationResource", - "RestorableMongodbCollectionGetResult", - "RestorableMongodbCollectionPropertiesResource", - "RestorableMongodbCollectionsListResult", - "RestorableMongodbDatabaseGetResult", - "RestorableMongodbDatabasePropertiesResource", - "RestorableMongodbDatabasesListResult", - "RestorableMongodbResourcesGetResult", - "RestorableMongodbResourcesListResult", - "RestorableSqlContainerGetResult", - "RestorableSqlContainerPropertiesResource", - "RestorableSqlContainerPropertiesResourceContainer", - "RestorableSqlContainersListResult", - "RestorableSqlDatabaseGetResult", - "RestorableSqlDatabasePropertiesResource", - "RestorableSqlDatabasePropertiesResourceDatabase", - "RestorableSqlDatabasesListResult", - "RestorableSqlResourcesGetResult", - "RestorableSqlResourcesListResult", - "RestorableTableGetResult", - "RestorableTablePropertiesResource", - "RestorableTableResourcesGetResult", - "RestorableTableResourcesListResult", - "RestorableTablesListResult", - "RestoreParameters", - "RestoreParametersBase", - "RetrieveThroughputParameters", - "RetrieveThroughputPropertiesResource", - "Role", - "SeedNode", - "ServiceResource", - "ServiceResourceCreateUpdateParameters", - "ServiceResourceCreateUpdateProperties", - "ServiceResourceListResult", - "ServiceResourceProperties", - "SpatialSpec", - "SqlContainerCreateUpdateParameters", - "SqlContainerGetPropertiesOptions", - "SqlContainerGetPropertiesResource", - "SqlContainerGetResults", - "SqlContainerListResult", - "SqlContainerResource", - "SqlDatabaseCreateUpdateParameters", - "SqlDatabaseGetPropertiesOptions", - "SqlDatabaseGetPropertiesResource", - "SqlDatabaseGetResults", - "SqlDatabaseListResult", - "SqlDatabaseResource", - "SqlDedicatedGatewayRegionalServiceResource", - "SqlDedicatedGatewayServiceResource", - "SqlDedicatedGatewayServiceResourceCreateUpdateProperties", - "SqlDedicatedGatewayServiceResourceProperties", - "SqlRoleAssignmentCreateUpdateParameters", - "SqlRoleAssignmentGetResults", - "SqlRoleAssignmentListResult", - "SqlRoleDefinitionCreateUpdateParameters", - "SqlRoleDefinitionGetResults", - "SqlRoleDefinitionListResult", - "SqlStoredProcedureCreateUpdateParameters", - "SqlStoredProcedureGetPropertiesResource", - "SqlStoredProcedureGetResults", - "SqlStoredProcedureListResult", - "SqlStoredProcedureResource", - "SqlTriggerCreateUpdateParameters", - "SqlTriggerGetPropertiesResource", - "SqlTriggerGetResults", - "SqlTriggerListResult", - "SqlTriggerResource", - "SqlUserDefinedFunctionCreateUpdateParameters", - "SqlUserDefinedFunctionGetPropertiesResource", - "SqlUserDefinedFunctionGetResults", - "SqlUserDefinedFunctionListResult", - "SqlUserDefinedFunctionResource", - "SystemData", - "TableCreateUpdateParameters", - "TableGetPropertiesOptions", - "TableGetPropertiesResource", - "TableGetResults", - "TableListResult", - "TableResource", - "ThroughputPolicyResource", - "ThroughputPoolAccountCreateParameters", - "ThroughputPoolAccountResource", - "ThroughputPoolAccountsListResult", - "ThroughputPoolResource", - "ThroughputPoolUpdate", - "ThroughputPoolsListResult", - "ThroughputSettingsGetPropertiesResource", - "ThroughputSettingsGetResults", - "ThroughputSettingsResource", - "ThroughputSettingsUpdateParameters", - "TrackedResource", - "UniqueKey", - "UniqueKeyPolicy", - "Usage", - "UsagesResult", - "VirtualNetworkRule", - "AccessRuleDirection", - "AnalyticalStorageSchemaType", - "ApiType", - "AuthenticationMethod", - "AutoReplicate", - "AzureConnectionType", - "BackupPolicyMigrationStatus", - "BackupPolicyType", - "BackupState", - "BackupStorageRedundancy", - "CapacityMode", - "CapacityModeTransitionStatus", - "ClusterType", - "CommandStatus", - "CompositePathSortOrder", - "ConflictResolutionMode", - "ConnectionState", - "ConnectorOffer", - "ContinuousTier", - "CreateMode", - "CreatedByType", - "DataTransferComponent", - "DataTransferJobMode", - "DataType", - "DatabaseAccountKind", - "DedicatedGatewayType", - "DefaultConsistencyLevel", - "DefaultPriorityLevel", - "EnableFullTextQuery", - "IndexKind", - "IndexingMode", - "IssueType", - "KeyKind", - "Kind", - "ManagedCassandraProvisioningState", - "ManagedCassandraResourceIdentityType", - "MinimalTlsVersion", - "MongoRoleDefinitionType", - "NetworkAclBypass", - "NetworkSecurityPerimeterConfigurationProvisioningState", - "NodeState", - "NodeStatus", - "NotebookWorkspaceName", - "OperationType", - "PartitionKind", - "PrimaryAggregationType", - "PublicNetworkAccess", - "ResourceAssociationAccessMode", - "ResourceIdentityType", - "RestoreMode", - "RoleDefinitionType", - "ScheduledEventStrategy", - "ServerVersion", - "ServiceSize", - "ServiceStatus", - "ServiceType", - "Severity", - "SpatialType", - "Status", - "SupportedActions", - "ThroughputPolicyType", - "TriggerOperation", - "TriggerType", - "Type", - "UnitType", -] -__all__.extend([p for p in _patch_all if p not in __all__]) -_patch_sdk() +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._models_py3 import ARMProxyResource +from ._models_py3 import ARMResourceProperties +from ._models_py3 import AccessRule +from ._models_py3 import AccessRuleProperties +from ._models_py3 import AccessRulePropertiesSubscriptionsItem +from ._models_py3 import AccountKeyMetadata +from ._models_py3 import AnalyticalStorageConfiguration +from ._models_py3 import ApiProperties +from ._models_py3 import AuthenticationMethodLdapProperties +from ._models_py3 import AutoUpgradePolicyResource +from ._models_py3 import AutoscaleSettings +from ._models_py3 import AutoscaleSettingsResource +from ._models_py3 import AzureBlobDataTransferDataSourceSink +from ._models_py3 import BackupInformation +from ._models_py3 import BackupPolicy +from ._models_py3 import BackupPolicyMigrationState +from ._models_py3 import BackupResource +from ._models_py3 import BackupSchedule +from ._models_py3 import BaseCosmosDataTransferDataSourceSink +from ._models_py3 import Capability +from ._models_py3 import Capacity +from ._models_py3 import CapacityModeChangeTransitionState +from ._models_py3 import CassandraClusterDataCenterNodeItem +from ._models_py3 import CassandraClusterPublicStatus +from ._models_py3 import CassandraClusterPublicStatusDataCentersItem +from ._models_py3 import CassandraError +from ._models_py3 import CassandraKeyspaceCreateUpdateParameters +from ._models_py3 import CassandraKeyspaceGetPropertiesOptions +from ._models_py3 import CassandraKeyspaceGetPropertiesResource +from ._models_py3 import CassandraKeyspaceGetResults +from ._models_py3 import CassandraKeyspaceListResult +from ._models_py3 import CassandraKeyspaceResource +from ._models_py3 import CassandraPartitionKey +from ._models_py3 import CassandraSchema +from ._models_py3 import CassandraTableCreateUpdateParameters +from ._models_py3 import CassandraTableGetPropertiesOptions +from ._models_py3 import CassandraTableGetPropertiesResource +from ._models_py3 import CassandraTableGetResults +from ._models_py3 import CassandraTableListResult +from ._models_py3 import CassandraTableResource +from ._models_py3 import CassandraViewCreateUpdateParameters +from ._models_py3 import CassandraViewGetPropertiesOptions +from ._models_py3 import CassandraViewGetPropertiesResource +from ._models_py3 import CassandraViewGetResults +from ._models_py3 import CassandraViewListResult +from ._models_py3 import CassandraViewResource +from ._models_py3 import Certificate +from ._models_py3 import ChaosFaultListResponse +from ._models_py3 import ChaosFaultResource +from ._models_py3 import ClientEncryptionIncludedPath +from ._models_py3 import ClientEncryptionKeyCreateUpdateParameters +from ._models_py3 import ClientEncryptionKeyGetPropertiesResource +from ._models_py3 import ClientEncryptionKeyGetResults +from ._models_py3 import ClientEncryptionKeyResource +from ._models_py3 import ClientEncryptionKeysListResult +from ._models_py3 import ClientEncryptionPolicy +from ._models_py3 import ClusterKey +from ._models_py3 import ClusterResource +from ._models_py3 import ClusterResourceProperties +from ._models_py3 import Column +from ._models_py3 import CommandOutput +from ._models_py3 import CommandPostBody +from ._models_py3 import CommandPublicResource +from ._models_py3 import CompositePath +from ._models_py3 import ComputedProperty +from ._models_py3 import ConflictResolutionPolicy +from ._models_py3 import ConnectionError +from ._models_py3 import ConsistencyPolicy +from ._models_py3 import ContainerPartitionKey +from ._models_py3 import ContinuousBackupInformation +from ._models_py3 import ContinuousBackupRestoreLocation +from ._models_py3 import ContinuousModeBackupPolicy +from ._models_py3 import ContinuousModeProperties +from ._models_py3 import CorsPolicy +from ._models_py3 import CosmosCassandraDataTransferDataSourceSink +from ._models_py3 import CosmosMongoDataTransferDataSourceSink +from ._models_py3 import CosmosMongoVCoreDataTransferDataSourceSink +from ._models_py3 import CosmosSqlDataTransferDataSourceSink +from ._models_py3 import CreateJobRequest +from ._models_py3 import CreateUpdateOptions +from ._models_py3 import DataCenterResource +from ._models_py3 import DataCenterResourceProperties +from ._models_py3 import DataTransferDataSourceSink +from ._models_py3 import DataTransferJobFeedResults +from ._models_py3 import DataTransferJobGetResults +from ._models_py3 import DataTransferJobProperties +from ._models_py3 import DataTransferRegionalServiceResource +from ._models_py3 import DataTransferServiceResource +from ._models_py3 import DataTransferServiceResourceCreateUpdateProperties +from ._models_py3 import DataTransferServiceResourceProperties +from ._models_py3 import DatabaseAccountConnectionString +from ._models_py3 import DatabaseAccountCreateUpdateParameters +from ._models_py3 import DatabaseAccountGetResults +from ._models_py3 import DatabaseAccountKeysMetadata +from ._models_py3 import DatabaseAccountListConnectionStringsResult +from ._models_py3 import DatabaseAccountListKeysResult +from ._models_py3 import DatabaseAccountListReadOnlyKeysResult +from ._models_py3 import DatabaseAccountRegenerateKeyParameters +from ._models_py3 import DatabaseAccountUpdateParameters +from ._models_py3 import DatabaseAccountsListResult +from ._models_py3 import DatabaseRestoreResource +from ._models_py3 import DiagnosticLogSettings +from ._models_py3 import ErrorAdditionalInfo +from ._models_py3 import ErrorDetail +from ._models_py3 import ErrorResponse +from ._models_py3 import ErrorResponseAutoGenerated +from ._models_py3 import ExcludedPath +from ._models_py3 import ExtendedResourceProperties +from ._models_py3 import FailoverPolicies +from ._models_py3 import FailoverPolicy +from ._models_py3 import GraphAPIComputeRegionalServiceResource +from ._models_py3 import GraphAPIComputeServiceResource +from ._models_py3 import GraphAPIComputeServiceResourceCreateUpdateProperties +from ._models_py3 import GraphAPIComputeServiceResourceProperties +from ._models_py3 import GraphResource +from ._models_py3 import GraphResourceCreateUpdateParameters +from ._models_py3 import GraphResourceGetPropertiesOptions +from ._models_py3 import GraphResourceGetPropertiesResource +from ._models_py3 import GraphResourceGetResults +from ._models_py3 import GraphResourcesListResult +from ._models_py3 import GremlinDatabaseCreateUpdateParameters +from ._models_py3 import GremlinDatabaseGetPropertiesOptions +from ._models_py3 import GremlinDatabaseGetPropertiesResource +from ._models_py3 import GremlinDatabaseGetResults +from ._models_py3 import GremlinDatabaseListResult +from ._models_py3 import GremlinDatabaseResource +from ._models_py3 import GremlinDatabaseRestoreResource +from ._models_py3 import GremlinGraphCreateUpdateParameters +from ._models_py3 import GremlinGraphGetPropertiesOptions +from ._models_py3 import GremlinGraphGetPropertiesResource +from ._models_py3 import GremlinGraphGetResults +from ._models_py3 import GremlinGraphListResult +from ._models_py3 import GremlinGraphResource +from ._models_py3 import IncludedPath +from ._models_py3 import Indexes +from ._models_py3 import IndexingPolicy +from ._models_py3 import IpAddressOrRange +from ._models_py3 import KeyWrapMetadata +from ._models_py3 import ListBackups +from ._models_py3 import ListClusters +from ._models_py3 import ListCommands +from ._models_py3 import ListDataCenters +from ._models_py3 import Location +from ._models_py3 import LocationGetResult +from ._models_py3 import LocationListResult +from ._models_py3 import LocationProperties +from ._models_py3 import ManagedCassandraARMResourceProperties +from ._models_py3 import ManagedCassandraManagedServiceIdentity +from ._models_py3 import ManagedCassandraReaperStatus +from ._models_py3 import ManagedServiceIdentity +from ._models_py3 import ManagedServiceIdentityUserAssignedIdentity +from ._models_py3 import MaterializedViewDefinition +from ._models_py3 import MaterializedViewsBuilderRegionalServiceResource +from ._models_py3 import MaterializedViewsBuilderServiceResource +from ._models_py3 import MaterializedViewsBuilderServiceResourceCreateUpdateProperties +from ._models_py3 import MaterializedViewsBuilderServiceResourceProperties +from ._models_py3 import MergeParameters +from ._models_py3 import Metric +from ._models_py3 import MetricAvailability +from ._models_py3 import MetricDefinition +from ._models_py3 import MetricDefinitionsListResult +from ._models_py3 import MetricListResult +from ._models_py3 import MetricName +from ._models_py3 import MetricValue +from ._models_py3 import MongoDBCollectionCreateUpdateParameters +from ._models_py3 import MongoDBCollectionGetPropertiesOptions +from ._models_py3 import MongoDBCollectionGetPropertiesResource +from ._models_py3 import MongoDBCollectionGetResults +from ._models_py3 import MongoDBCollectionListResult +from ._models_py3 import MongoDBCollectionResource +from ._models_py3 import MongoDBDatabaseCreateUpdateParameters +from ._models_py3 import MongoDBDatabaseGetPropertiesOptions +from ._models_py3 import MongoDBDatabaseGetPropertiesResource +from ._models_py3 import MongoDBDatabaseGetResults +from ._models_py3 import MongoDBDatabaseListResult +from ._models_py3 import MongoDBDatabaseResource +from ._models_py3 import MongoIndex +from ._models_py3 import MongoIndexKeys +from ._models_py3 import MongoIndexOptions +from ._models_py3 import MongoRoleDefinitionCreateUpdateParameters +from ._models_py3 import MongoRoleDefinitionGetResults +from ._models_py3 import MongoRoleDefinitionListResult +from ._models_py3 import MongoUserDefinitionCreateUpdateParameters +from ._models_py3 import MongoUserDefinitionGetResults +from ._models_py3 import MongoUserDefinitionListResult +from ._models_py3 import NetworkSecurityPerimeter +from ._models_py3 import NetworkSecurityPerimeterConfiguration +from ._models_py3 import NetworkSecurityPerimeterConfigurationListResult +from ._models_py3 import NetworkSecurityPerimeterConfigurationProperties +from ._models_py3 import NetworkSecurityProfile +from ._models_py3 import NotebookWorkspace +from ._models_py3 import NotebookWorkspaceConnectionInfoResult +from ._models_py3 import NotebookWorkspaceCreateUpdateParameters +from ._models_py3 import NotebookWorkspaceListResult +from ._models_py3 import Operation +from ._models_py3 import OperationDisplay +from ._models_py3 import OperationListResult +from ._models_py3 import OptionsResource +from ._models_py3 import PartitionMetric +from ._models_py3 import PartitionMetricListResult +from ._models_py3 import PartitionUsage +from ._models_py3 import PartitionUsagesResult +from ._models_py3 import PercentileMetric +from ._models_py3 import PercentileMetricListResult +from ._models_py3 import PercentileMetricValue +from ._models_py3 import PeriodicModeBackupPolicy +from ._models_py3 import PeriodicModeProperties +from ._models_py3 import Permission +from ._models_py3 import PhysicalPartitionId +from ._models_py3 import PhysicalPartitionStorageInfo +from ._models_py3 import PhysicalPartitionStorageInfoCollection +from ._models_py3 import PhysicalPartitionThroughputInfoProperties +from ._models_py3 import PhysicalPartitionThroughputInfoResource +from ._models_py3 import PhysicalPartitionThroughputInfoResult +from ._models_py3 import PhysicalPartitionThroughputInfoResultPropertiesResource +from ._models_py3 import PrivateEndpointConnection +from ._models_py3 import PrivateEndpointConnectionListResult +from ._models_py3 import PrivateEndpointProperty +from ._models_py3 import PrivateLinkResource +from ._models_py3 import PrivateLinkResourceListResult +from ._models_py3 import PrivateLinkServiceConnectionStateProperty +from ._models_py3 import Privilege +from ._models_py3 import PrivilegeResource +from ._models_py3 import ProvisioningIssue +from ._models_py3 import ProvisioningIssueProperties +from ._models_py3 import ProxyResource +from ._models_py3 import RedistributeThroughputParameters +from ._models_py3 import RedistributeThroughputPropertiesResource +from ._models_py3 import RegionForOnlineOffline +from ._models_py3 import RegionalServiceResource +from ._models_py3 import Resource +from ._models_py3 import ResourceAssociation +from ._models_py3 import ResourceRestoreParameters +from ._models_py3 import RestorableDatabaseAccountGetResult +from ._models_py3 import RestorableDatabaseAccountsListResult +from ._models_py3 import RestorableGremlinDatabaseGetResult +from ._models_py3 import RestorableGremlinDatabasePropertiesResource +from ._models_py3 import RestorableGremlinDatabasesListResult +from ._models_py3 import RestorableGremlinGraphGetResult +from ._models_py3 import RestorableGremlinGraphPropertiesResource +from ._models_py3 import RestorableGremlinGraphsListResult +from ._models_py3 import RestorableGremlinResourcesGetResult +from ._models_py3 import RestorableGremlinResourcesListResult +from ._models_py3 import RestorableLocationResource +from ._models_py3 import RestorableMongodbCollectionGetResult +from ._models_py3 import RestorableMongodbCollectionPropertiesResource +from ._models_py3 import RestorableMongodbCollectionsListResult +from ._models_py3 import RestorableMongodbDatabaseGetResult +from ._models_py3 import RestorableMongodbDatabasePropertiesResource +from ._models_py3 import RestorableMongodbDatabasesListResult +from ._models_py3 import RestorableMongodbResourcesGetResult +from ._models_py3 import RestorableMongodbResourcesListResult +from ._models_py3 import RestorableSqlContainerGetResult +from ._models_py3 import RestorableSqlContainerPropertiesResource +from ._models_py3 import RestorableSqlContainerPropertiesResourceContainer +from ._models_py3 import RestorableSqlContainersListResult +from ._models_py3 import RestorableSqlDatabaseGetResult +from ._models_py3 import RestorableSqlDatabasePropertiesResource +from ._models_py3 import RestorableSqlDatabasePropertiesResourceDatabase +from ._models_py3 import RestorableSqlDatabasesListResult +from ._models_py3 import RestorableSqlResourcesGetResult +from ._models_py3 import RestorableSqlResourcesListResult +from ._models_py3 import RestorableTableGetResult +from ._models_py3 import RestorableTablePropertiesResource +from ._models_py3 import RestorableTableResourcesGetResult +from ._models_py3 import RestorableTableResourcesListResult +from ._models_py3 import RestorableTablesListResult +from ._models_py3 import RestoreParameters +from ._models_py3 import RestoreParametersBase +from ._models_py3 import RetrieveThroughputParameters +from ._models_py3 import RetrieveThroughputPropertiesResource +from ._models_py3 import Role +from ._models_py3 import SeedNode +from ._models_py3 import ServiceResource +from ._models_py3 import ServiceResourceCreateUpdateParameters +from ._models_py3 import ServiceResourceCreateUpdateProperties +from ._models_py3 import ServiceResourceListResult +from ._models_py3 import ServiceResourceProperties +from ._models_py3 import SpatialSpec +from ._models_py3 import SqlContainerCreateUpdateParameters +from ._models_py3 import SqlContainerGetPropertiesOptions +from ._models_py3 import SqlContainerGetPropertiesResource +from ._models_py3 import SqlContainerGetResults +from ._models_py3 import SqlContainerListResult +from ._models_py3 import SqlContainerResource +from ._models_py3 import SqlDatabaseCreateUpdateParameters +from ._models_py3 import SqlDatabaseGetPropertiesOptions +from ._models_py3 import SqlDatabaseGetPropertiesResource +from ._models_py3 import SqlDatabaseGetResults +from ._models_py3 import SqlDatabaseListResult +from ._models_py3 import SqlDatabaseResource +from ._models_py3 import SqlDedicatedGatewayRegionalServiceResource +from ._models_py3 import SqlDedicatedGatewayServiceResource +from ._models_py3 import SqlDedicatedGatewayServiceResourceCreateUpdateProperties +from ._models_py3 import SqlDedicatedGatewayServiceResourceProperties +from ._models_py3 import SqlRoleAssignmentCreateUpdateParameters +from ._models_py3 import SqlRoleAssignmentGetResults +from ._models_py3 import SqlRoleAssignmentListResult +from ._models_py3 import SqlRoleDefinitionCreateUpdateParameters +from ._models_py3 import SqlRoleDefinitionGetResults +from ._models_py3 import SqlRoleDefinitionListResult +from ._models_py3 import SqlStoredProcedureCreateUpdateParameters +from ._models_py3 import SqlStoredProcedureGetPropertiesResource +from ._models_py3 import SqlStoredProcedureGetResults +from ._models_py3 import SqlStoredProcedureListResult +from ._models_py3 import SqlStoredProcedureResource +from ._models_py3 import SqlTriggerCreateUpdateParameters +from ._models_py3 import SqlTriggerGetPropertiesResource +from ._models_py3 import SqlTriggerGetResults +from ._models_py3 import SqlTriggerListResult +from ._models_py3 import SqlTriggerResource +from ._models_py3 import SqlUserDefinedFunctionCreateUpdateParameters +from ._models_py3 import SqlUserDefinedFunctionGetPropertiesResource +from ._models_py3 import SqlUserDefinedFunctionGetResults +from ._models_py3 import SqlUserDefinedFunctionListResult +from ._models_py3 import SqlUserDefinedFunctionResource +from ._models_py3 import SystemData +from ._models_py3 import TableCreateUpdateParameters +from ._models_py3 import TableGetPropertiesOptions +from ._models_py3 import TableGetPropertiesResource +from ._models_py3 import TableGetResults +from ._models_py3 import TableListResult +from ._models_py3 import TableResource +from ._models_py3 import ThroughputPolicyResource +from ._models_py3 import ThroughputPoolAccountCreateParameters +from ._models_py3 import ThroughputPoolAccountResource +from ._models_py3 import ThroughputPoolAccountsListResult +from ._models_py3 import ThroughputPoolResource +from ._models_py3 import ThroughputPoolUpdate +from ._models_py3 import ThroughputPoolsListResult +from ._models_py3 import ThroughputSettingsGetPropertiesResource +from ._models_py3 import ThroughputSettingsGetResults +from ._models_py3 import ThroughputSettingsResource +from ._models_py3 import ThroughputSettingsUpdateParameters +from ._models_py3 import TrackedResource +from ._models_py3 import UniqueKey +from ._models_py3 import UniqueKeyPolicy +from ._models_py3 import Usage +from ._models_py3 import UsagesResult +from ._models_py3 import VirtualNetworkRule + +from ._cosmos_db_management_client_enums import AccessRuleDirection +from ._cosmos_db_management_client_enums import AnalyticalStorageSchemaType +from ._cosmos_db_management_client_enums import ApiType +from ._cosmos_db_management_client_enums import AuthenticationMethod +from ._cosmos_db_management_client_enums import AutoReplicate +from ._cosmos_db_management_client_enums import AzureConnectionType +from ._cosmos_db_management_client_enums import BackupPolicyMigrationStatus +from ._cosmos_db_management_client_enums import BackupPolicyType +from ._cosmos_db_management_client_enums import BackupState +from ._cosmos_db_management_client_enums import BackupStorageRedundancy +from ._cosmos_db_management_client_enums import CapacityMode +from ._cosmos_db_management_client_enums import CapacityModeTransitionStatus +from ._cosmos_db_management_client_enums import ClusterType +from ._cosmos_db_management_client_enums import CommandStatus +from ._cosmos_db_management_client_enums import CompositePathSortOrder +from ._cosmos_db_management_client_enums import ConflictResolutionMode +from ._cosmos_db_management_client_enums import ConnectionState +from ._cosmos_db_management_client_enums import ConnectorOffer +from ._cosmos_db_management_client_enums import ContinuousTier +from ._cosmos_db_management_client_enums import CreateMode +from ._cosmos_db_management_client_enums import CreatedByType +from ._cosmos_db_management_client_enums import DataTransferComponent +from ._cosmos_db_management_client_enums import DataTransferJobMode +from ._cosmos_db_management_client_enums import DataType +from ._cosmos_db_management_client_enums import DatabaseAccountKind +from ._cosmos_db_management_client_enums import DedicatedGatewayType +from ._cosmos_db_management_client_enums import DefaultConsistencyLevel +from ._cosmos_db_management_client_enums import DefaultPriorityLevel +from ._cosmos_db_management_client_enums import EnableFullTextQuery +from ._cosmos_db_management_client_enums import IndexKind +from ._cosmos_db_management_client_enums import IndexingMode +from ._cosmos_db_management_client_enums import IssueType +from ._cosmos_db_management_client_enums import KeyKind +from ._cosmos_db_management_client_enums import Kind +from ._cosmos_db_management_client_enums import ManagedCassandraProvisioningState +from ._cosmos_db_management_client_enums import ManagedCassandraResourceIdentityType +from ._cosmos_db_management_client_enums import MinimalTlsVersion +from ._cosmos_db_management_client_enums import MongoRoleDefinitionType +from ._cosmos_db_management_client_enums import NetworkAclBypass +from ._cosmos_db_management_client_enums import NetworkSecurityPerimeterConfigurationProvisioningState +from ._cosmos_db_management_client_enums import NodeState +from ._cosmos_db_management_client_enums import NodeStatus +from ._cosmos_db_management_client_enums import NotebookWorkspaceName +from ._cosmos_db_management_client_enums import OperationType +from ._cosmos_db_management_client_enums import PartitionKind +from ._cosmos_db_management_client_enums import PrimaryAggregationType +from ._cosmos_db_management_client_enums import PublicNetworkAccess +from ._cosmos_db_management_client_enums import ResourceAssociationAccessMode +from ._cosmos_db_management_client_enums import ResourceIdentityType +from ._cosmos_db_management_client_enums import RestoreMode +from ._cosmos_db_management_client_enums import RoleDefinitionType +from ._cosmos_db_management_client_enums import ScheduledEventStrategy +from ._cosmos_db_management_client_enums import ServerVersion +from ._cosmos_db_management_client_enums import ServiceSize +from ._cosmos_db_management_client_enums import ServiceStatus +from ._cosmos_db_management_client_enums import ServiceType +from ._cosmos_db_management_client_enums import Severity +from ._cosmos_db_management_client_enums import SpatialType +from ._cosmos_db_management_client_enums import Status +from ._cosmos_db_management_client_enums import SupportedActions +from ._cosmos_db_management_client_enums import ThroughputPolicyType +from ._cosmos_db_management_client_enums import TriggerOperation +from ._cosmos_db_management_client_enums import TriggerType +from ._cosmos_db_management_client_enums import Type +from ._cosmos_db_management_client_enums import UnitType +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ARMProxyResource", + "ARMResourceProperties", + "AccessRule", + "AccessRuleProperties", + "AccessRulePropertiesSubscriptionsItem", + "AccountKeyMetadata", + "AnalyticalStorageConfiguration", + "ApiProperties", + "AuthenticationMethodLdapProperties", + "AutoUpgradePolicyResource", + "AutoscaleSettings", + "AutoscaleSettingsResource", + "AzureBlobDataTransferDataSourceSink", + "BackupInformation", + "BackupPolicy", + "BackupPolicyMigrationState", + "BackupResource", + "BackupSchedule", + "BaseCosmosDataTransferDataSourceSink", + "Capability", + "Capacity", + "CapacityModeChangeTransitionState", + "CassandraClusterDataCenterNodeItem", + "CassandraClusterPublicStatus", + "CassandraClusterPublicStatusDataCentersItem", + "CassandraError", + "CassandraKeyspaceCreateUpdateParameters", + "CassandraKeyspaceGetPropertiesOptions", + "CassandraKeyspaceGetPropertiesResource", + "CassandraKeyspaceGetResults", + "CassandraKeyspaceListResult", + "CassandraKeyspaceResource", + "CassandraPartitionKey", + "CassandraSchema", + "CassandraTableCreateUpdateParameters", + "CassandraTableGetPropertiesOptions", + "CassandraTableGetPropertiesResource", + "CassandraTableGetResults", + "CassandraTableListResult", + "CassandraTableResource", + "CassandraViewCreateUpdateParameters", + "CassandraViewGetPropertiesOptions", + "CassandraViewGetPropertiesResource", + "CassandraViewGetResults", + "CassandraViewListResult", + "CassandraViewResource", + "Certificate", + "ChaosFaultListResponse", + "ChaosFaultResource", + "ClientEncryptionIncludedPath", + "ClientEncryptionKeyCreateUpdateParameters", + "ClientEncryptionKeyGetPropertiesResource", + "ClientEncryptionKeyGetResults", + "ClientEncryptionKeyResource", + "ClientEncryptionKeysListResult", + "ClientEncryptionPolicy", + "ClusterKey", + "ClusterResource", + "ClusterResourceProperties", + "Column", + "CommandOutput", + "CommandPostBody", + "CommandPublicResource", + "CompositePath", + "ComputedProperty", + "ConflictResolutionPolicy", + "ConnectionError", + "ConsistencyPolicy", + "ContainerPartitionKey", + "ContinuousBackupInformation", + "ContinuousBackupRestoreLocation", + "ContinuousModeBackupPolicy", + "ContinuousModeProperties", + "CorsPolicy", + "CosmosCassandraDataTransferDataSourceSink", + "CosmosMongoDataTransferDataSourceSink", + "CosmosMongoVCoreDataTransferDataSourceSink", + "CosmosSqlDataTransferDataSourceSink", + "CreateJobRequest", + "CreateUpdateOptions", + "DataCenterResource", + "DataCenterResourceProperties", + "DataTransferDataSourceSink", + "DataTransferJobFeedResults", + "DataTransferJobGetResults", + "DataTransferJobProperties", + "DataTransferRegionalServiceResource", + "DataTransferServiceResource", + "DataTransferServiceResourceCreateUpdateProperties", + "DataTransferServiceResourceProperties", + "DatabaseAccountConnectionString", + "DatabaseAccountCreateUpdateParameters", + "DatabaseAccountGetResults", + "DatabaseAccountKeysMetadata", + "DatabaseAccountListConnectionStringsResult", + "DatabaseAccountListKeysResult", + "DatabaseAccountListReadOnlyKeysResult", + "DatabaseAccountRegenerateKeyParameters", + "DatabaseAccountUpdateParameters", + "DatabaseAccountsListResult", + "DatabaseRestoreResource", + "DiagnosticLogSettings", + "ErrorAdditionalInfo", + "ErrorDetail", + "ErrorResponse", + "ErrorResponseAutoGenerated", + "ExcludedPath", + "ExtendedResourceProperties", + "FailoverPolicies", + "FailoverPolicy", + "GraphAPIComputeRegionalServiceResource", + "GraphAPIComputeServiceResource", + "GraphAPIComputeServiceResourceCreateUpdateProperties", + "GraphAPIComputeServiceResourceProperties", + "GraphResource", + "GraphResourceCreateUpdateParameters", + "GraphResourceGetPropertiesOptions", + "GraphResourceGetPropertiesResource", + "GraphResourceGetResults", + "GraphResourcesListResult", + "GremlinDatabaseCreateUpdateParameters", + "GremlinDatabaseGetPropertiesOptions", + "GremlinDatabaseGetPropertiesResource", + "GremlinDatabaseGetResults", + "GremlinDatabaseListResult", + "GremlinDatabaseResource", + "GremlinDatabaseRestoreResource", + "GremlinGraphCreateUpdateParameters", + "GremlinGraphGetPropertiesOptions", + "GremlinGraphGetPropertiesResource", + "GremlinGraphGetResults", + "GremlinGraphListResult", + "GremlinGraphResource", + "IncludedPath", + "Indexes", + "IndexingPolicy", + "IpAddressOrRange", + "KeyWrapMetadata", + "ListBackups", + "ListClusters", + "ListCommands", + "ListDataCenters", + "Location", + "LocationGetResult", + "LocationListResult", + "LocationProperties", + "ManagedCassandraARMResourceProperties", + "ManagedCassandraManagedServiceIdentity", + "ManagedCassandraReaperStatus", + "ManagedServiceIdentity", + "ManagedServiceIdentityUserAssignedIdentity", + "MaterializedViewDefinition", + "MaterializedViewsBuilderRegionalServiceResource", + "MaterializedViewsBuilderServiceResource", + "MaterializedViewsBuilderServiceResourceCreateUpdateProperties", + "MaterializedViewsBuilderServiceResourceProperties", + "MergeParameters", + "Metric", + "MetricAvailability", + "MetricDefinition", + "MetricDefinitionsListResult", + "MetricListResult", + "MetricName", + "MetricValue", + "MongoDBCollectionCreateUpdateParameters", + "MongoDBCollectionGetPropertiesOptions", + "MongoDBCollectionGetPropertiesResource", + "MongoDBCollectionGetResults", + "MongoDBCollectionListResult", + "MongoDBCollectionResource", + "MongoDBDatabaseCreateUpdateParameters", + "MongoDBDatabaseGetPropertiesOptions", + "MongoDBDatabaseGetPropertiesResource", + "MongoDBDatabaseGetResults", + "MongoDBDatabaseListResult", + "MongoDBDatabaseResource", + "MongoIndex", + "MongoIndexKeys", + "MongoIndexOptions", + "MongoRoleDefinitionCreateUpdateParameters", + "MongoRoleDefinitionGetResults", + "MongoRoleDefinitionListResult", + "MongoUserDefinitionCreateUpdateParameters", + "MongoUserDefinitionGetResults", + "MongoUserDefinitionListResult", + "NetworkSecurityPerimeter", + "NetworkSecurityPerimeterConfiguration", + "NetworkSecurityPerimeterConfigurationListResult", + "NetworkSecurityPerimeterConfigurationProperties", + "NetworkSecurityProfile", + "NotebookWorkspace", + "NotebookWorkspaceConnectionInfoResult", + "NotebookWorkspaceCreateUpdateParameters", + "NotebookWorkspaceListResult", + "Operation", + "OperationDisplay", + "OperationListResult", + "OptionsResource", + "PartitionMetric", + "PartitionMetricListResult", + "PartitionUsage", + "PartitionUsagesResult", + "PercentileMetric", + "PercentileMetricListResult", + "PercentileMetricValue", + "PeriodicModeBackupPolicy", + "PeriodicModeProperties", + "Permission", + "PhysicalPartitionId", + "PhysicalPartitionStorageInfo", + "PhysicalPartitionStorageInfoCollection", + "PhysicalPartitionThroughputInfoProperties", + "PhysicalPartitionThroughputInfoResource", + "PhysicalPartitionThroughputInfoResult", + "PhysicalPartitionThroughputInfoResultPropertiesResource", + "PrivateEndpointConnection", + "PrivateEndpointConnectionListResult", + "PrivateEndpointProperty", + "PrivateLinkResource", + "PrivateLinkResourceListResult", + "PrivateLinkServiceConnectionStateProperty", + "Privilege", + "PrivilegeResource", + "ProvisioningIssue", + "ProvisioningIssueProperties", + "ProxyResource", + "RedistributeThroughputParameters", + "RedistributeThroughputPropertiesResource", + "RegionForOnlineOffline", + "RegionalServiceResource", + "Resource", + "ResourceAssociation", + "ResourceRestoreParameters", + "RestorableDatabaseAccountGetResult", + "RestorableDatabaseAccountsListResult", + "RestorableGremlinDatabaseGetResult", + "RestorableGremlinDatabasePropertiesResource", + "RestorableGremlinDatabasesListResult", + "RestorableGremlinGraphGetResult", + "RestorableGremlinGraphPropertiesResource", + "RestorableGremlinGraphsListResult", + "RestorableGremlinResourcesGetResult", + "RestorableGremlinResourcesListResult", + "RestorableLocationResource", + "RestorableMongodbCollectionGetResult", + "RestorableMongodbCollectionPropertiesResource", + "RestorableMongodbCollectionsListResult", + "RestorableMongodbDatabaseGetResult", + "RestorableMongodbDatabasePropertiesResource", + "RestorableMongodbDatabasesListResult", + "RestorableMongodbResourcesGetResult", + "RestorableMongodbResourcesListResult", + "RestorableSqlContainerGetResult", + "RestorableSqlContainerPropertiesResource", + "RestorableSqlContainerPropertiesResourceContainer", + "RestorableSqlContainersListResult", + "RestorableSqlDatabaseGetResult", + "RestorableSqlDatabasePropertiesResource", + "RestorableSqlDatabasePropertiesResourceDatabase", + "RestorableSqlDatabasesListResult", + "RestorableSqlResourcesGetResult", + "RestorableSqlResourcesListResult", + "RestorableTableGetResult", + "RestorableTablePropertiesResource", + "RestorableTableResourcesGetResult", + "RestorableTableResourcesListResult", + "RestorableTablesListResult", + "RestoreParameters", + "RestoreParametersBase", + "RetrieveThroughputParameters", + "RetrieveThroughputPropertiesResource", + "Role", + "SeedNode", + "ServiceResource", + "ServiceResourceCreateUpdateParameters", + "ServiceResourceCreateUpdateProperties", + "ServiceResourceListResult", + "ServiceResourceProperties", + "SpatialSpec", + "SqlContainerCreateUpdateParameters", + "SqlContainerGetPropertiesOptions", + "SqlContainerGetPropertiesResource", + "SqlContainerGetResults", + "SqlContainerListResult", + "SqlContainerResource", + "SqlDatabaseCreateUpdateParameters", + "SqlDatabaseGetPropertiesOptions", + "SqlDatabaseGetPropertiesResource", + "SqlDatabaseGetResults", + "SqlDatabaseListResult", + "SqlDatabaseResource", + "SqlDedicatedGatewayRegionalServiceResource", + "SqlDedicatedGatewayServiceResource", + "SqlDedicatedGatewayServiceResourceCreateUpdateProperties", + "SqlDedicatedGatewayServiceResourceProperties", + "SqlRoleAssignmentCreateUpdateParameters", + "SqlRoleAssignmentGetResults", + "SqlRoleAssignmentListResult", + "SqlRoleDefinitionCreateUpdateParameters", + "SqlRoleDefinitionGetResults", + "SqlRoleDefinitionListResult", + "SqlStoredProcedureCreateUpdateParameters", + "SqlStoredProcedureGetPropertiesResource", + "SqlStoredProcedureGetResults", + "SqlStoredProcedureListResult", + "SqlStoredProcedureResource", + "SqlTriggerCreateUpdateParameters", + "SqlTriggerGetPropertiesResource", + "SqlTriggerGetResults", + "SqlTriggerListResult", + "SqlTriggerResource", + "SqlUserDefinedFunctionCreateUpdateParameters", + "SqlUserDefinedFunctionGetPropertiesResource", + "SqlUserDefinedFunctionGetResults", + "SqlUserDefinedFunctionListResult", + "SqlUserDefinedFunctionResource", + "SystemData", + "TableCreateUpdateParameters", + "TableGetPropertiesOptions", + "TableGetPropertiesResource", + "TableGetResults", + "TableListResult", + "TableResource", + "ThroughputPolicyResource", + "ThroughputPoolAccountCreateParameters", + "ThroughputPoolAccountResource", + "ThroughputPoolAccountsListResult", + "ThroughputPoolResource", + "ThroughputPoolUpdate", + "ThroughputPoolsListResult", + "ThroughputSettingsGetPropertiesResource", + "ThroughputSettingsGetResults", + "ThroughputSettingsResource", + "ThroughputSettingsUpdateParameters", + "TrackedResource", + "UniqueKey", + "UniqueKeyPolicy", + "Usage", + "UsagesResult", + "VirtualNetworkRule", + "AccessRuleDirection", + "AnalyticalStorageSchemaType", + "ApiType", + "AuthenticationMethod", + "AutoReplicate", + "AzureConnectionType", + "BackupPolicyMigrationStatus", + "BackupPolicyType", + "BackupState", + "BackupStorageRedundancy", + "CapacityMode", + "CapacityModeTransitionStatus", + "ClusterType", + "CommandStatus", + "CompositePathSortOrder", + "ConflictResolutionMode", + "ConnectionState", + "ConnectorOffer", + "ContinuousTier", + "CreateMode", + "CreatedByType", + "DataTransferComponent", + "DataTransferJobMode", + "DataType", + "DatabaseAccountKind", + "DedicatedGatewayType", + "DefaultConsistencyLevel", + "DefaultPriorityLevel", + "EnableFullTextQuery", + "IndexKind", + "IndexingMode", + "IssueType", + "KeyKind", + "Kind", + "ManagedCassandraProvisioningState", + "ManagedCassandraResourceIdentityType", + "MinimalTlsVersion", + "MongoRoleDefinitionType", + "NetworkAclBypass", + "NetworkSecurityPerimeterConfigurationProvisioningState", + "NodeState", + "NodeStatus", + "NotebookWorkspaceName", + "OperationType", + "PartitionKind", + "PrimaryAggregationType", + "PublicNetworkAccess", + "ResourceAssociationAccessMode", + "ResourceIdentityType", + "RestoreMode", + "RoleDefinitionType", + "ScheduledEventStrategy", + "ServerVersion", + "ServiceSize", + "ServiceStatus", + "ServiceType", + "Severity", + "SpatialType", + "Status", + "SupportedActions", + "ThroughputPolicyType", + "TriggerOperation", + "TriggerType", + "Type", + "UnitType", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/models/_cosmos_db_management_client_enums.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/models/_cosmos_db_management_client_enums.py index 1f2823bdadb..fd1f8e81d5a 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/models/_cosmos_db_management_client_enums.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/models/_cosmos_db_management_client_enums.py @@ -1,594 +1,594 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from enum import Enum -from azure.core import CaseInsensitiveEnumMeta - - -class AccessRuleDirection(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Direction of Access Rule.""" - - INBOUND = "Inbound" - """Applies to inbound network traffic to the secured resources.""" - OUTBOUND = "Outbound" - """Applies to outbound network traffic from the secured resources""" - - -class AnalyticalStorageSchemaType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Describes the types of schema for analytical storage.""" - - WELL_DEFINED = "WellDefined" - FULL_FIDELITY = "FullFidelity" - - -class ApiType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Enum to indicate the API type of the restorable database account.""" - - MONGO_DB = "MongoDB" - GREMLIN = "Gremlin" - CASSANDRA = "Cassandra" - TABLE = "Table" - SQL = "Sql" - GREMLIN_V2 = "GremlinV2" - - -class AuthenticationMethod(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Which authentication method Cassandra should use to authenticate clients. 'None' turns off - authentication, so should not be used except in emergencies. 'Cassandra' is the default - password based authentication. The default is 'Cassandra'. - """ - - NONE = "None" - CASSANDRA = "Cassandra" - LDAP = "Ldap" - - -class AutoReplicate(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The form of AutoReplicate that is being used by this cluster.""" - - NONE = "None" - SYSTEM_KEYSPACES = "SystemKeyspaces" - ALL_KEYSPACES = "AllKeyspaces" - - -class AzureConnectionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """How to connect to the azure services needed for running the cluster.""" - - NONE = "None" - VPN = "VPN" - - -class BackupPolicyMigrationStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Describes the status of migration between backup policy types.""" - - INVALID = "Invalid" - IN_PROGRESS = "InProgress" - COMPLETED = "Completed" - FAILED = "Failed" - - -class BackupPolicyType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Describes the mode of backups.""" - - PERIODIC = "Periodic" - CONTINUOUS = "Continuous" - - -class BackupState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The current state of the backup.""" - - INITIATED = "Initiated" - IN_PROGRESS = "InProgress" - SUCCEEDED = "Succeeded" - FAILED = "Failed" - - -class BackupStorageRedundancy(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Enum to indicate type of backup storage redundancy.""" - - GEO = "Geo" - LOCAL = "Local" - ZONE = "Zone" - - -class CapacityMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Indicates the capacity mode of the account.""" - - NONE = "None" - PROVISIONED = "Provisioned" - SERVERLESS = "Serverless" - - -class CapacityModeTransitionStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The transition status of capacity mode.""" - - INVALID = "Invalid" - INITIALIZED = "Initialized" - IN_PROGRESS = "InProgress" - COMPLETED = "Completed" - FAILED = "Failed" - - -class ClusterType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of the cluster. If set to Production, some operations might not be permitted on cluster.""" - - PRODUCTION = "Production" - NON_PRODUCTION = "NonProduction" - - -class CommandStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Status of the command.""" - - DONE = "Done" - RUNNING = "Running" - ENQUEUE = "Enqueue" - PROCESSING = "Processing" - FINISHED = "Finished" - FAILED = "Failed" - - -class CompositePathSortOrder(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Sort order for composite paths.""" - - ASCENDING = "ascending" - DESCENDING = "descending" - - -class ConflictResolutionMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Indicates the conflict resolution mode.""" - - LAST_WRITER_WINS = "LastWriterWins" - CUSTOM = "Custom" - - -class ConnectionState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The kind of connection error that occurred.""" - - UNKNOWN = "Unknown" - OK = "OK" - OPERATOR_TO_DATA_CENTER_NETWORK_ERROR = "OperatorToDataCenterNetworkError" - DATACENTER_TO_DATACENTER_NETWORK_ERROR = "DatacenterToDatacenterNetworkError" - INTERNAL_OPERATOR_TO_DATA_CENTER_CERTIFICATE_ERROR = "InternalOperatorToDataCenterCertificateError" - INTERNAL_ERROR = "InternalError" - - -class ConnectorOffer(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The cassandra connector offer type for the Cosmos DB C* database account.""" - - SMALL = "Small" - - -class ContinuousTier(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Enum to indicate type of Continuous backup tier.""" - - CONTINUOUS7_DAYS = "Continuous7Days" - CONTINUOUS30_DAYS = "Continuous30Days" - - -class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The type of identity that created the resource.""" - - USER = "User" - APPLICATION = "Application" - MANAGED_IDENTITY = "ManagedIdentity" - KEY = "Key" - - -class CreateMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Enum to indicate the mode of account creation.""" - - DEFAULT = "Default" - RESTORE = "Restore" - - -class DatabaseAccountKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Indicates the type of database account. This can only be set at database account creation.""" - - GLOBAL_DOCUMENT_DB = "GlobalDocumentDB" - MONGO_DB = "MongoDB" - PARSE = "Parse" - - -class DataTransferComponent(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """DataTransferComponent.""" - - COSMOS_DB_CASSANDRA = "CosmosDBCassandra" - COSMOS_DB_MONGO = "CosmosDBMongo" - COSMOS_DB_MONGO_V_CORE = "CosmosDBMongoVCore" - COSMOS_DB_SQL = "CosmosDBSql" - AZURE_BLOB_STORAGE = "AzureBlobStorage" - - -class DataTransferJobMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Mode of job execution.""" - - OFFLINE = "Offline" - ONLINE = "Online" - - -class DataType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The datatype for which the indexing behavior is applied to.""" - - STRING = "String" - NUMBER = "Number" - POINT = "Point" - POLYGON = "Polygon" - LINE_STRING = "LineString" - MULTI_POLYGON = "MultiPolygon" - - -class DedicatedGatewayType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """DedicatedGatewayType for the service.""" - - INTEGRATED_CACHE = "IntegratedCache" - DISTRIBUTED_QUERY = "DistributedQuery" - - -class DefaultConsistencyLevel(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The default consistency level and configuration settings of the Cosmos DB account.""" - - EVENTUAL = "Eventual" - SESSION = "Session" - BOUNDED_STALENESS = "BoundedStaleness" - STRONG = "Strong" - CONSISTENT_PREFIX = "ConsistentPrefix" - - -class DefaultPriorityLevel(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Enum to indicate default priorityLevel of requests.""" - - HIGH = "High" - LOW = "Low" - - -class EnableFullTextQuery(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Describe the level of detail with which queries are to be logged.""" - - NONE = "None" - TRUE = "True" - FALSE = "False" - - -class IndexingMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Indicates the indexing mode.""" - - CONSISTENT = "consistent" - LAZY = "lazy" - NONE = "none" - - -class IndexKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Indicates the type of index.""" - - HASH = "Hash" - RANGE = "Range" - SPATIAL = "Spatial" - - -class IssueType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of issue.""" - - UNKNOWN = "Unknown" - """Unknown issue type""" - CONFIGURATION_PROPAGATION_FAILURE = "ConfigurationPropagationFailure" - """An error occurred while applying the network security perimeter (NSP) configuration.""" - MISSING_PERIMETER_CONFIGURATION = "MissingPerimeterConfiguration" - """A network connectivity issue is happening on the resource which could be addressed either by - adding new resources to the network security perimeter (NSP) or by modifying access rules.""" - MISSING_IDENTITY_CONFIGURATION = "MissingIdentityConfiguration" - """An managed identity hasn't been associated with the resource. The resource will still be able - to validate inbound traffic from the network security perimeter (NSP) or matching inbound - access rules, but it won't be able to perform outbound access as a member of the NSP.""" - - -class KeyKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The access key to regenerate.""" - - PRIMARY = "primary" - SECONDARY = "secondary" - PRIMARY_READONLY = "primaryReadonly" - SECONDARY_READONLY = "secondaryReadonly" - - -class Kind(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Kind of the connection string key.""" - - PRIMARY = "Primary" - SECONDARY = "Secondary" - PRIMARY_READONLY = "PrimaryReadonly" - SECONDARY_READONLY = "SecondaryReadonly" - - -class ManagedCassandraProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The status of the resource at the time the operation was called.""" - - CREATING = "Creating" - UPDATING = "Updating" - DELETING = "Deleting" - SUCCEEDED = "Succeeded" - FAILED = "Failed" - CANCELED = "Canceled" - - -class ManagedCassandraResourceIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The type of the resource.""" - - SYSTEM_ASSIGNED = "SystemAssigned" - NONE = "None" - - -class MinimalTlsVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Indicates the minimum allowed Tls version. The default is Tls 1.0, except for Cassandra and - Mongo API's, which only work with Tls 1.2. - """ - - TLS = "Tls" - TLS11 = "Tls11" - TLS12 = "Tls12" - - -class MongoRoleDefinitionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Indicates whether the Role Definition was built-in or user created.""" - - BUILT_IN_ROLE = "BuiltInRole" - CUSTOM_ROLE = "CustomRole" - - -class NetworkAclBypass(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Indicates what services are allowed to bypass firewall checks.""" - - NONE = "None" - AZURE_SERVICES = "AzureServices" - - -class NetworkSecurityPerimeterConfigurationProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Provisioning state of a network security perimeter configuration that is being created or - updated. - """ - - SUCCEEDED = "Succeeded" - CREATING = "Creating" - UPDATING = "Updating" - DELETING = "Deleting" - ACCEPTED = "Accepted" - FAILED = "Failed" - CANCELED = "Canceled" - - -class NodeState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The state of the node in Cassandra ring.""" - - NORMAL = "Normal" - LEAVING = "Leaving" - JOINING = "Joining" - MOVING = "Moving" - STOPPED = "Stopped" - - -class NodeStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Indicates whether the node is functioning or not.""" - - UP = "Up" - DOWN = "Down" - - -class NotebookWorkspaceName(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """NotebookWorkspaceName.""" - - DEFAULT = "default" - - -class OperationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Enum to indicate the operation type of the event.""" - - CREATE = "Create" - REPLACE = "Replace" - DELETE = "Delete" - RECREATE = "Recreate" - SYSTEM_OPERATION = "SystemOperation" - - -class PartitionKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Indicates the kind of algorithm used for partitioning. For MultiHash, multiple partition keys - (upto three maximum) are supported for container create. - """ - - HASH = "Hash" - RANGE = "Range" - MULTI_HASH = "MultiHash" - - -class PrimaryAggregationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The primary aggregation type of the metric.""" - - NONE = "None" - AVERAGE = "Average" - TOTAL = "Total" - MINIMUM = "Minimum" - MAXIMUM = "Maximum" - LAST = "Last" - - -class PublicNetworkAccess(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Whether requests from Public Network are allowed.""" - - ENABLED = "Enabled" - DISABLED = "Disabled" - SECURED_BY_PERIMETER = "SecuredByPerimeter" - - -class ResourceAssociationAccessMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Access mode of the resource association.""" - - ENFORCED = "Enforced" - """Enforced access mode - traffic to the resource that failed access checks is blocked""" - LEARNING = "Learning" - """Learning access mode - traffic to the resource is enabled for analysis but not blocked""" - AUDIT = "Audit" - """Audit access mode - traffic to the resource that fails access checks is logged but not blocked""" - - -class ResourceIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The type of identity used for the resource. The type 'SystemAssigned,UserAssigned' includes - both an implicitly created identity and a set of user assigned identities. The type 'None' will - remove any identities from the service. - """ - - SYSTEM_ASSIGNED = "SystemAssigned" - USER_ASSIGNED = "UserAssigned" - SYSTEM_ASSIGNED_USER_ASSIGNED = "SystemAssigned,UserAssigned" - NONE = "None" - - -class RestoreMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Describes the mode of the restore.""" - - POINT_IN_TIME = "PointInTime" - - -class RoleDefinitionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Indicates whether the Role Definition was built-in or user created.""" - - BUILT_IN_ROLE = "BuiltInRole" - CUSTOM_ROLE = "CustomRole" - - -class ScheduledEventStrategy(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """How the nodes in the cluster react to scheduled events.""" - - IGNORE = "Ignore" - STOP_ANY = "StopAny" - STOP_BY_RACK = "StopByRack" - - -class ServerVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Describes the version of the MongoDB account.""" - - THREE2 = "3.2" - THREE6 = "3.6" - FOUR0 = "4.0" - FOUR2 = "4.2" - FIVE0 = "5.0" - SIX0 = "6.0" - SEVEN0 = "7.0" - - -class ServiceSize(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Instance type for the service.""" - - COSMOS_D4_S = "Cosmos.D4s" - COSMOS_D8_S = "Cosmos.D8s" - COSMOS_D16_S = "Cosmos.D16s" - - -class ServiceStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Describes the status of a service.""" - - CREATING = "Creating" - RUNNING = "Running" - UPDATING = "Updating" - DELETING = "Deleting" - ERROR = "Error" - STOPPED = "Stopped" - - -class ServiceType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """ServiceType for the service.""" - - SQL_DEDICATED_GATEWAY = "SqlDedicatedGateway" - DATA_TRANSFER = "DataTransfer" - GRAPH_API_COMPUTE = "GraphAPICompute" - MATERIALIZED_VIEWS_BUILDER = "MaterializedViewsBuilder" - - -class Severity(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Severity of the issue.""" - - WARNING = "Warning" - ERROR = "Error" - - -class SpatialType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Indicates the spatial type of index.""" - - POINT = "Point" - LINE_STRING = "LineString" - POLYGON = "Polygon" - MULTI_POLYGON = "MultiPolygon" - - -class Status(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Enum to indicate current buildout status of the region.""" - - UNINITIALIZED = "Uninitialized" - INITIALIZING = "Initializing" - INTERNALLY_READY = "InternallyReady" - ONLINE = "Online" - DELETING = "Deleting" - SUCCEEDED = "Succeeded" - FAILED = "Failed" - CANCELED = "Canceled" - UPDATING = "Updating" - - -class SupportedActions(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Indicates whether what action to take for the Chaos Fault.""" - - ENABLE = "Enable" - DISABLE = "Disable" - - -class ThroughputPolicyType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """ThroughputPolicy to apply for throughput redistribution.""" - - NONE = "none" - EQUAL = "equal" - CUSTOM = "custom" - - -class TriggerOperation(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The operation the trigger is associated with.""" - - ALL = "All" - CREATE = "Create" - UPDATE = "Update" - DELETE = "Delete" - REPLACE = "Replace" - - -class TriggerType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of the Trigger.""" - - PRE = "Pre" - POST = "Post" - - -class Type(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of the connection string.""" - - SQL = "Sql" - TABLE = "Table" - MONGO_DB = "MongoDB" - CASSANDRA = "Cassandra" - CASSANDRA_CONNECTOR_METADATA = "CassandraConnectorMetadata" - GREMLIN = "Gremlin" - SQL_DEDICATED_GATEWAY = "SqlDedicatedGateway" - GREMLIN_V2 = "GremlinV2" - UNDEFINED = "Undefined" - - -class UnitType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The unit of the metric.""" - - COUNT = "Count" - BYTES = "Bytes" - SECONDS = "Seconds" - PERCENT = "Percent" - COUNT_PER_SECOND = "CountPerSecond" - BYTES_PER_SECOND = "BytesPerSecond" - MILLISECONDS = "Milliseconds" +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class AccessRuleDirection(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Direction of Access Rule.""" + + INBOUND = "Inbound" + """Applies to inbound network traffic to the secured resources.""" + OUTBOUND = "Outbound" + """Applies to outbound network traffic from the secured resources""" + + +class AnalyticalStorageSchemaType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Describes the types of schema for analytical storage.""" + + WELL_DEFINED = "WellDefined" + FULL_FIDELITY = "FullFidelity" + + +class ApiType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Enum to indicate the API type of the restorable database account.""" + + MONGO_DB = "MongoDB" + GREMLIN = "Gremlin" + CASSANDRA = "Cassandra" + TABLE = "Table" + SQL = "Sql" + GREMLIN_V2 = "GremlinV2" + + +class AuthenticationMethod(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Which authentication method Cassandra should use to authenticate clients. 'None' turns off + authentication, so should not be used except in emergencies. 'Cassandra' is the default + password based authentication. The default is 'Cassandra'. + """ + + NONE = "None" + CASSANDRA = "Cassandra" + LDAP = "Ldap" + + +class AutoReplicate(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The form of AutoReplicate that is being used by this cluster.""" + + NONE = "None" + SYSTEM_KEYSPACES = "SystemKeyspaces" + ALL_KEYSPACES = "AllKeyspaces" + + +class AzureConnectionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """How to connect to the azure services needed for running the cluster.""" + + NONE = "None" + VPN = "VPN" + + +class BackupPolicyMigrationStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Describes the status of migration between backup policy types.""" + + INVALID = "Invalid" + IN_PROGRESS = "InProgress" + COMPLETED = "Completed" + FAILED = "Failed" + + +class BackupPolicyType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Describes the mode of backups.""" + + PERIODIC = "Periodic" + CONTINUOUS = "Continuous" + + +class BackupState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The current state of the backup.""" + + INITIATED = "Initiated" + IN_PROGRESS = "InProgress" + SUCCEEDED = "Succeeded" + FAILED = "Failed" + + +class BackupStorageRedundancy(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Enum to indicate type of backup storage redundancy.""" + + GEO = "Geo" + LOCAL = "Local" + ZONE = "Zone" + + +class CapacityMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Indicates the capacity mode of the account.""" + + NONE = "None" + PROVISIONED = "Provisioned" + SERVERLESS = "Serverless" + + +class CapacityModeTransitionStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The transition status of capacity mode.""" + + INVALID = "Invalid" + INITIALIZED = "Initialized" + IN_PROGRESS = "InProgress" + COMPLETED = "Completed" + FAILED = "Failed" + + +class ClusterType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Type of the cluster. If set to Production, some operations might not be permitted on cluster.""" + + PRODUCTION = "Production" + NON_PRODUCTION = "NonProduction" + + +class CommandStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Status of the command.""" + + DONE = "Done" + RUNNING = "Running" + ENQUEUE = "Enqueue" + PROCESSING = "Processing" + FINISHED = "Finished" + FAILED = "Failed" + + +class CompositePathSortOrder(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Sort order for composite paths.""" + + ASCENDING = "ascending" + DESCENDING = "descending" + + +class ConflictResolutionMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Indicates the conflict resolution mode.""" + + LAST_WRITER_WINS = "LastWriterWins" + CUSTOM = "Custom" + + +class ConnectionState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The kind of connection error that occurred.""" + + UNKNOWN = "Unknown" + OK = "OK" + OPERATOR_TO_DATA_CENTER_NETWORK_ERROR = "OperatorToDataCenterNetworkError" + DATACENTER_TO_DATACENTER_NETWORK_ERROR = "DatacenterToDatacenterNetworkError" + INTERNAL_OPERATOR_TO_DATA_CENTER_CERTIFICATE_ERROR = "InternalOperatorToDataCenterCertificateError" + INTERNAL_ERROR = "InternalError" + + +class ConnectorOffer(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The cassandra connector offer type for the Cosmos DB C* database account.""" + + SMALL = "Small" + + +class ContinuousTier(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Enum to indicate type of Continuous backup tier.""" + + CONTINUOUS7_DAYS = "Continuous7Days" + CONTINUOUS30_DAYS = "Continuous30Days" + + +class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of identity that created the resource.""" + + USER = "User" + APPLICATION = "Application" + MANAGED_IDENTITY = "ManagedIdentity" + KEY = "Key" + + +class CreateMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Enum to indicate the mode of account creation.""" + + DEFAULT = "Default" + RESTORE = "Restore" + + +class DatabaseAccountKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Indicates the type of database account. This can only be set at database account creation.""" + + GLOBAL_DOCUMENT_DB = "GlobalDocumentDB" + MONGO_DB = "MongoDB" + PARSE = "Parse" + + +class DataTransferComponent(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """DataTransferComponent.""" + + COSMOS_DB_CASSANDRA = "CosmosDBCassandra" + COSMOS_DB_MONGO = "CosmosDBMongo" + COSMOS_DB_MONGO_V_CORE = "CosmosDBMongoVCore" + COSMOS_DB_SQL = "CosmosDBSql" + AZURE_BLOB_STORAGE = "AzureBlobStorage" + + +class DataTransferJobMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Mode of job execution.""" + + OFFLINE = "Offline" + ONLINE = "Online" + + +class DataType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The datatype for which the indexing behavior is applied to.""" + + STRING = "String" + NUMBER = "Number" + POINT = "Point" + POLYGON = "Polygon" + LINE_STRING = "LineString" + MULTI_POLYGON = "MultiPolygon" + + +class DedicatedGatewayType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """DedicatedGatewayType for the service.""" + + INTEGRATED_CACHE = "IntegratedCache" + DISTRIBUTED_QUERY = "DistributedQuery" + + +class DefaultConsistencyLevel(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The default consistency level and configuration settings of the Cosmos DB account.""" + + EVENTUAL = "Eventual" + SESSION = "Session" + BOUNDED_STALENESS = "BoundedStaleness" + STRONG = "Strong" + CONSISTENT_PREFIX = "ConsistentPrefix" + + +class DefaultPriorityLevel(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Enum to indicate default priorityLevel of requests.""" + + HIGH = "High" + LOW = "Low" + + +class EnableFullTextQuery(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Describe the level of detail with which queries are to be logged.""" + + NONE = "None" + TRUE = "True" + FALSE = "False" + + +class IndexingMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Indicates the indexing mode.""" + + CONSISTENT = "consistent" + LAZY = "lazy" + NONE = "none" + + +class IndexKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Indicates the type of index.""" + + HASH = "Hash" + RANGE = "Range" + SPATIAL = "Spatial" + + +class IssueType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Type of issue.""" + + UNKNOWN = "Unknown" + """Unknown issue type""" + CONFIGURATION_PROPAGATION_FAILURE = "ConfigurationPropagationFailure" + """An error occurred while applying the network security perimeter (NSP) configuration.""" + MISSING_PERIMETER_CONFIGURATION = "MissingPerimeterConfiguration" + """A network connectivity issue is happening on the resource which could be addressed either by + adding new resources to the network security perimeter (NSP) or by modifying access rules.""" + MISSING_IDENTITY_CONFIGURATION = "MissingIdentityConfiguration" + """An managed identity hasn't been associated with the resource. The resource will still be able + to validate inbound traffic from the network security perimeter (NSP) or matching inbound + access rules, but it won't be able to perform outbound access as a member of the NSP.""" + + +class KeyKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The access key to regenerate.""" + + PRIMARY = "primary" + SECONDARY = "secondary" + PRIMARY_READONLY = "primaryReadonly" + SECONDARY_READONLY = "secondaryReadonly" + + +class Kind(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Kind of the connection string key.""" + + PRIMARY = "Primary" + SECONDARY = "Secondary" + PRIMARY_READONLY = "PrimaryReadonly" + SECONDARY_READONLY = "SecondaryReadonly" + + +class ManagedCassandraProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The status of the resource at the time the operation was called.""" + + CREATING = "Creating" + UPDATING = "Updating" + DELETING = "Deleting" + SUCCEEDED = "Succeeded" + FAILED = "Failed" + CANCELED = "Canceled" + + +class ManagedCassandraResourceIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the resource.""" + + SYSTEM_ASSIGNED = "SystemAssigned" + NONE = "None" + + +class MinimalTlsVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Indicates the minimum allowed Tls version. The default is Tls 1.0, except for Cassandra and + Mongo API's, which only work with Tls 1.2. + """ + + TLS = "Tls" + TLS11 = "Tls11" + TLS12 = "Tls12" + + +class MongoRoleDefinitionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Indicates whether the Role Definition was built-in or user created.""" + + BUILT_IN_ROLE = "BuiltInRole" + CUSTOM_ROLE = "CustomRole" + + +class NetworkAclBypass(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Indicates what services are allowed to bypass firewall checks.""" + + NONE = "None" + AZURE_SERVICES = "AzureServices" + + +class NetworkSecurityPerimeterConfigurationProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Provisioning state of a network security perimeter configuration that is being created or + updated. + """ + + SUCCEEDED = "Succeeded" + CREATING = "Creating" + UPDATING = "Updating" + DELETING = "Deleting" + ACCEPTED = "Accepted" + FAILED = "Failed" + CANCELED = "Canceled" + + +class NodeState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The state of the node in Cassandra ring.""" + + NORMAL = "Normal" + LEAVING = "Leaving" + JOINING = "Joining" + MOVING = "Moving" + STOPPED = "Stopped" + + +class NodeStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Indicates whether the node is functioning or not.""" + + UP = "Up" + DOWN = "Down" + + +class NotebookWorkspaceName(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """NotebookWorkspaceName.""" + + DEFAULT = "default" + + +class OperationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Enum to indicate the operation type of the event.""" + + CREATE = "Create" + REPLACE = "Replace" + DELETE = "Delete" + RECREATE = "Recreate" + SYSTEM_OPERATION = "SystemOperation" + + +class PartitionKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Indicates the kind of algorithm used for partitioning. For MultiHash, multiple partition keys + (upto three maximum) are supported for container create. + """ + + HASH = "Hash" + RANGE = "Range" + MULTI_HASH = "MultiHash" + + +class PrimaryAggregationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The primary aggregation type of the metric.""" + + NONE = "None" + AVERAGE = "Average" + TOTAL = "Total" + MINIMUM = "Minimum" + MAXIMUM = "Maximum" + LAST = "Last" + + +class PublicNetworkAccess(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Whether requests from Public Network are allowed.""" + + ENABLED = "Enabled" + DISABLED = "Disabled" + SECURED_BY_PERIMETER = "SecuredByPerimeter" + + +class ResourceAssociationAccessMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Access mode of the resource association.""" + + ENFORCED = "Enforced" + """Enforced access mode - traffic to the resource that failed access checks is blocked""" + LEARNING = "Learning" + """Learning access mode - traffic to the resource is enabled for analysis but not blocked""" + AUDIT = "Audit" + """Audit access mode - traffic to the resource that fails access checks is logged but not blocked""" + + +class ResourceIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of identity used for the resource. The type 'SystemAssigned,UserAssigned' includes + both an implicitly created identity and a set of user assigned identities. The type 'None' will + remove any identities from the service. + """ + + SYSTEM_ASSIGNED = "SystemAssigned" + USER_ASSIGNED = "UserAssigned" + SYSTEM_ASSIGNED_USER_ASSIGNED = "SystemAssigned,UserAssigned" + NONE = "None" + + +class RestoreMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Describes the mode of the restore.""" + + POINT_IN_TIME = "PointInTime" + + +class RoleDefinitionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Indicates whether the Role Definition was built-in or user created.""" + + BUILT_IN_ROLE = "BuiltInRole" + CUSTOM_ROLE = "CustomRole" + + +class ScheduledEventStrategy(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """How the nodes in the cluster react to scheduled events.""" + + IGNORE = "Ignore" + STOP_ANY = "StopAny" + STOP_BY_RACK = "StopByRack" + + +class ServerVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Describes the version of the MongoDB account.""" + + THREE2 = "3.2" + THREE6 = "3.6" + FOUR0 = "4.0" + FOUR2 = "4.2" + FIVE0 = "5.0" + SIX0 = "6.0" + SEVEN0 = "7.0" + + +class ServiceSize(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Instance type for the service.""" + + COSMOS_D4_S = "Cosmos.D4s" + COSMOS_D8_S = "Cosmos.D8s" + COSMOS_D16_S = "Cosmos.D16s" + + +class ServiceStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Describes the status of a service.""" + + CREATING = "Creating" + RUNNING = "Running" + UPDATING = "Updating" + DELETING = "Deleting" + ERROR = "Error" + STOPPED = "Stopped" + + +class ServiceType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """ServiceType for the service.""" + + SQL_DEDICATED_GATEWAY = "SqlDedicatedGateway" + DATA_TRANSFER = "DataTransfer" + GRAPH_API_COMPUTE = "GraphAPICompute" + MATERIALIZED_VIEWS_BUILDER = "MaterializedViewsBuilder" + + +class Severity(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Severity of the issue.""" + + WARNING = "Warning" + ERROR = "Error" + + +class SpatialType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Indicates the spatial type of index.""" + + POINT = "Point" + LINE_STRING = "LineString" + POLYGON = "Polygon" + MULTI_POLYGON = "MultiPolygon" + + +class Status(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Enum to indicate current buildout status of the region.""" + + UNINITIALIZED = "Uninitialized" + INITIALIZING = "Initializing" + INTERNALLY_READY = "InternallyReady" + ONLINE = "Online" + DELETING = "Deleting" + SUCCEEDED = "Succeeded" + FAILED = "Failed" + CANCELED = "Canceled" + UPDATING = "Updating" + + +class SupportedActions(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Indicates whether what action to take for the Chaos Fault.""" + + ENABLE = "Enable" + DISABLE = "Disable" + + +class ThroughputPolicyType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """ThroughputPolicy to apply for throughput redistribution.""" + + NONE = "none" + EQUAL = "equal" + CUSTOM = "custom" + + +class TriggerOperation(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The operation the trigger is associated with.""" + + ALL = "All" + CREATE = "Create" + UPDATE = "Update" + DELETE = "Delete" + REPLACE = "Replace" + + +class TriggerType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Type of the Trigger.""" + + PRE = "Pre" + POST = "Post" + + +class Type(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Type of the connection string.""" + + SQL = "Sql" + TABLE = "Table" + MONGO_DB = "MongoDB" + CASSANDRA = "Cassandra" + CASSANDRA_CONNECTOR_METADATA = "CassandraConnectorMetadata" + GREMLIN = "Gremlin" + SQL_DEDICATED_GATEWAY = "SqlDedicatedGateway" + GREMLIN_V2 = "GremlinV2" + UNDEFINED = "Undefined" + + +class UnitType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The unit of the metric.""" + + COUNT = "Count" + BYTES = "Bytes" + SECONDS = "Seconds" + PERCENT = "Percent" + COUNT_PER_SECOND = "CountPerSecond" + BYTES_PER_SECOND = "BytesPerSecond" + MILLISECONDS = "Milliseconds" diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/models/_models_py3.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/models/_models_py3.py index 3fd3c68a4ef..1d9a9c000db 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/models/_models_py3.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/models/_models_py3.py @@ -1,16791 +1,16791 @@ -# coding=utf-8 -# pylint: disable=too-many-lines -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -import datetime -import sys -from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union - -from .. import _serialization - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from .. import models as _models -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - - -class AccessRule(_serialization.Model): - """Access rule in a network security perimeter configuration profile. - - :ivar name: Name of the access rule. - :vartype name: str - :ivar properties: Properties of Access Rule. - :vartype properties: ~azure.mgmt.cosmosdb.models.AccessRuleProperties - """ - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "properties": {"key": "properties", "type": "AccessRuleProperties"}, - } - - def __init__( - self, *, name: Optional[str] = None, properties: Optional["_models.AccessRuleProperties"] = None, **kwargs: Any - ) -> None: - """ - :keyword name: Name of the access rule. - :paramtype name: str - :keyword properties: Properties of Access Rule. - :paramtype properties: ~azure.mgmt.cosmosdb.models.AccessRuleProperties - """ - super().__init__(**kwargs) - self.name = name - self.properties = properties - - -class AccessRuleProperties(_serialization.Model): - """Properties of Access Rule. - - :ivar direction: Direction of Access Rule. Known values are: "Inbound" and "Outbound". - :vartype direction: str or ~azure.mgmt.cosmosdb.models.AccessRuleDirection - :ivar address_prefixes: Address prefixes in the CIDR format for inbound rules. - :vartype address_prefixes: list[str] - :ivar subscriptions: Subscriptions for inbound rules. - :vartype subscriptions: list[~azure.mgmt.cosmosdb.models.AccessRulePropertiesSubscriptionsItem] - :ivar network_security_perimeters: Network security perimeters for inbound rules. - :vartype network_security_perimeters: - list[~azure.mgmt.cosmosdb.models.NetworkSecurityPerimeter] - :ivar fully_qualified_domain_names: Fully qualified domain names (FQDN) for outbound rules. - :vartype fully_qualified_domain_names: list[str] - :ivar email_addresses: Email addresses for outbound rules. - :vartype email_addresses: list[str] - :ivar phone_numbers: Phone numbers for outbound rules. - :vartype phone_numbers: list[str] - """ - - _attribute_map = { - "direction": {"key": "direction", "type": "str"}, - "address_prefixes": {"key": "addressPrefixes", "type": "[str]"}, - "subscriptions": {"key": "subscriptions", "type": "[AccessRulePropertiesSubscriptionsItem]"}, - "network_security_perimeters": {"key": "networkSecurityPerimeters", "type": "[NetworkSecurityPerimeter]"}, - "fully_qualified_domain_names": {"key": "fullyQualifiedDomainNames", "type": "[str]"}, - "email_addresses": {"key": "emailAddresses", "type": "[str]"}, - "phone_numbers": {"key": "phoneNumbers", "type": "[str]"}, - } - - def __init__( - self, - *, - direction: Optional[Union[str, "_models.AccessRuleDirection"]] = None, - address_prefixes: Optional[List[str]] = None, - subscriptions: Optional[List["_models.AccessRulePropertiesSubscriptionsItem"]] = None, - network_security_perimeters: Optional[List["_models.NetworkSecurityPerimeter"]] = None, - fully_qualified_domain_names: Optional[List[str]] = None, - email_addresses: Optional[List[str]] = None, - phone_numbers: Optional[List[str]] = None, - **kwargs: Any - ) -> None: - """ - :keyword direction: Direction of Access Rule. Known values are: "Inbound" and "Outbound". - :paramtype direction: str or ~azure.mgmt.cosmosdb.models.AccessRuleDirection - :keyword address_prefixes: Address prefixes in the CIDR format for inbound rules. - :paramtype address_prefixes: list[str] - :keyword subscriptions: Subscriptions for inbound rules. - :paramtype subscriptions: - list[~azure.mgmt.cosmosdb.models.AccessRulePropertiesSubscriptionsItem] - :keyword network_security_perimeters: Network security perimeters for inbound rules. - :paramtype network_security_perimeters: - list[~azure.mgmt.cosmosdb.models.NetworkSecurityPerimeter] - :keyword fully_qualified_domain_names: Fully qualified domain names (FQDN) for outbound rules. - :paramtype fully_qualified_domain_names: list[str] - :keyword email_addresses: Email addresses for outbound rules. - :paramtype email_addresses: list[str] - :keyword phone_numbers: Phone numbers for outbound rules. - :paramtype phone_numbers: list[str] - """ - super().__init__(**kwargs) - self.direction = direction - self.address_prefixes = address_prefixes - self.subscriptions = subscriptions - self.network_security_perimeters = network_security_perimeters - self.fully_qualified_domain_names = fully_qualified_domain_names - self.email_addresses = email_addresses - self.phone_numbers = phone_numbers - - -class AccessRulePropertiesSubscriptionsItem(_serialization.Model): - """Subscription identifiers. - - :ivar id: The fully qualified Azure resource ID of the subscription e.g. - ('/subscriptions/00000000-0000-0000-0000-000000000000'). - :vartype id: str - """ - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - } - - def __init__(self, *, id: Optional[str] = None, **kwargs: Any) -> None: # pylint: disable=redefined-builtin - """ - :keyword id: The fully qualified Azure resource ID of the subscription e.g. - ('/subscriptions/00000000-0000-0000-0000-000000000000'). - :paramtype id: str - """ - super().__init__(**kwargs) - self.id = id - - -class AccountKeyMetadata(_serialization.Model): - """The metadata related to an access key for a given database account. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar generation_time: Generation time in UTC of the key in ISO-8601 format. If the value is - missing from the object, it means that the last key regeneration was triggered before - 2022-06-18. - :vartype generation_time: ~datetime.datetime - """ - - _validation = { - "generation_time": {"readonly": True}, - } - - _attribute_map = { - "generation_time": {"key": "generationTime", "type": "iso-8601"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.generation_time = None - - -class AnalyticalStorageConfiguration(_serialization.Model): - """Analytical storage specific properties. - - :ivar schema_type: Describes the types of schema for analytical storage. Known values are: - "WellDefined" and "FullFidelity". - :vartype schema_type: str or ~azure.mgmt.cosmosdb.models.AnalyticalStorageSchemaType - """ - - _attribute_map = { - "schema_type": {"key": "schemaType", "type": "str"}, - } - - def __init__( - self, *, schema_type: Optional[Union[str, "_models.AnalyticalStorageSchemaType"]] = None, **kwargs: Any - ) -> None: - """ - :keyword schema_type: Describes the types of schema for analytical storage. Known values are: - "WellDefined" and "FullFidelity". - :paramtype schema_type: str or ~azure.mgmt.cosmosdb.models.AnalyticalStorageSchemaType - """ - super().__init__(**kwargs) - self.schema_type = schema_type - - -class ApiProperties(_serialization.Model): - """ApiProperties. - - :ivar server_version: Describes the version of the MongoDB account. Known values are: "3.2", - "3.6", "4.0", "4.2", "5.0", "6.0", and "7.0". - :vartype server_version: str or ~azure.mgmt.cosmosdb.models.ServerVersion - """ - - _attribute_map = { - "server_version": {"key": "serverVersion", "type": "str"}, - } - - def __init__(self, *, server_version: Optional[Union[str, "_models.ServerVersion"]] = None, **kwargs: Any) -> None: - """ - :keyword server_version: Describes the version of the MongoDB account. Known values are: "3.2", - "3.6", "4.0", "4.2", "5.0", "6.0", and "7.0". - :paramtype server_version: str or ~azure.mgmt.cosmosdb.models.ServerVersion - """ - super().__init__(**kwargs) - self.server_version = server_version - - -class ARMProxyResource(_serialization.Model): - """The resource model definition for a ARM proxy resource. It will have everything other than - required location and tags. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the database account. - :vartype id: str - :ivar name: The name of the database account. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - - -class ARMResourceProperties(_serialization.Model): - """The core properties of ARM resources. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - } - - def __init__( - self, - *, - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.location = location - self.tags = tags - self.identity = identity - - -class AuthenticationMethodLdapProperties(_serialization.Model): - """Ldap authentication method properties. This feature is in preview. - - :ivar server_hostname: Hostname of the LDAP server. - :vartype server_hostname: str - :ivar server_port: Port of the LDAP server. - :vartype server_port: int - :ivar service_user_distinguished_name: Distinguished name of the look up user account, who can - look up user details on authentication. - :vartype service_user_distinguished_name: str - :ivar service_user_password: Password of the look up user. - :vartype service_user_password: str - :ivar search_base_distinguished_name: Distinguished name of the object to start the recursive - search of users from. - :vartype search_base_distinguished_name: str - :ivar search_filter_template: Template to use for searching. Defaults to (cn=%s) where %s will - be replaced by the username used to login. - :vartype search_filter_template: str - :ivar server_certificates: - :vartype server_certificates: list[~azure.mgmt.cosmosdb.models.Certificate] - :ivar connection_timeout_in_ms: Timeout for connecting to the LDAP server in miliseconds. The - default is 5000 ms. - :vartype connection_timeout_in_ms: int - """ - - _attribute_map = { - "server_hostname": {"key": "serverHostname", "type": "str"}, - "server_port": {"key": "serverPort", "type": "int"}, - "service_user_distinguished_name": {"key": "serviceUserDistinguishedName", "type": "str"}, - "service_user_password": {"key": "serviceUserPassword", "type": "str"}, - "search_base_distinguished_name": {"key": "searchBaseDistinguishedName", "type": "str"}, - "search_filter_template": {"key": "searchFilterTemplate", "type": "str"}, - "server_certificates": {"key": "serverCertificates", "type": "[Certificate]"}, - "connection_timeout_in_ms": {"key": "connectionTimeoutInMs", "type": "int"}, - } - - def __init__( - self, - *, - server_hostname: Optional[str] = None, - server_port: Optional[int] = None, - service_user_distinguished_name: Optional[str] = None, - service_user_password: Optional[str] = None, - search_base_distinguished_name: Optional[str] = None, - search_filter_template: Optional[str] = None, - server_certificates: Optional[List["_models.Certificate"]] = None, - connection_timeout_in_ms: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword server_hostname: Hostname of the LDAP server. - :paramtype server_hostname: str - :keyword server_port: Port of the LDAP server. - :paramtype server_port: int - :keyword service_user_distinguished_name: Distinguished name of the look up user account, who - can look up user details on authentication. - :paramtype service_user_distinguished_name: str - :keyword service_user_password: Password of the look up user. - :paramtype service_user_password: str - :keyword search_base_distinguished_name: Distinguished name of the object to start the - recursive search of users from. - :paramtype search_base_distinguished_name: str - :keyword search_filter_template: Template to use for searching. Defaults to (cn=%s) where %s - will be replaced by the username used to login. - :paramtype search_filter_template: str - :keyword server_certificates: - :paramtype server_certificates: list[~azure.mgmt.cosmosdb.models.Certificate] - :keyword connection_timeout_in_ms: Timeout for connecting to the LDAP server in miliseconds. - The default is 5000 ms. - :paramtype connection_timeout_in_ms: int - """ - super().__init__(**kwargs) - self.server_hostname = server_hostname - self.server_port = server_port - self.service_user_distinguished_name = service_user_distinguished_name - self.service_user_password = service_user_password - self.search_base_distinguished_name = search_base_distinguished_name - self.search_filter_template = search_filter_template - self.server_certificates = server_certificates - self.connection_timeout_in_ms = connection_timeout_in_ms - - -class AutoscaleSettings(_serialization.Model): - """AutoscaleSettings. - - :ivar max_throughput: Represents maximum throughput, the resource can scale up to. - :vartype max_throughput: int - """ - - _attribute_map = { - "max_throughput": {"key": "maxThroughput", "type": "int"}, - } - - def __init__(self, *, max_throughput: Optional[int] = None, **kwargs: Any) -> None: - """ - :keyword max_throughput: Represents maximum throughput, the resource can scale up to. - :paramtype max_throughput: int - """ - super().__init__(**kwargs) - self.max_throughput = max_throughput - - -class AutoscaleSettingsResource(_serialization.Model): - """Cosmos DB provisioned throughput settings object. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar max_throughput: Represents maximum throughput container can scale up to. Required. - :vartype max_throughput: int - :ivar auto_upgrade_policy: Cosmos DB resource auto-upgrade policy. - :vartype auto_upgrade_policy: ~azure.mgmt.cosmosdb.models.AutoUpgradePolicyResource - :ivar target_max_throughput: Represents target maximum throughput container can scale up to - once offer is no longer in pending state. - :vartype target_max_throughput: int - """ - - _validation = { - "max_throughput": {"required": True}, - "target_max_throughput": {"readonly": True}, - } - - _attribute_map = { - "max_throughput": {"key": "maxThroughput", "type": "int"}, - "auto_upgrade_policy": {"key": "autoUpgradePolicy", "type": "AutoUpgradePolicyResource"}, - "target_max_throughput": {"key": "targetMaxThroughput", "type": "int"}, - } - - def __init__( - self, - *, - max_throughput: int, - auto_upgrade_policy: Optional["_models.AutoUpgradePolicyResource"] = None, - **kwargs: Any - ) -> None: - """ - :keyword max_throughput: Represents maximum throughput container can scale up to. Required. - :paramtype max_throughput: int - :keyword auto_upgrade_policy: Cosmos DB resource auto-upgrade policy. - :paramtype auto_upgrade_policy: ~azure.mgmt.cosmosdb.models.AutoUpgradePolicyResource - """ - super().__init__(**kwargs) - self.max_throughput = max_throughput - self.auto_upgrade_policy = auto_upgrade_policy - self.target_max_throughput = None - - -class AutoUpgradePolicyResource(_serialization.Model): - """Cosmos DB resource auto-upgrade policy. - - :ivar throughput_policy: Represents throughput policy which service must adhere to for - auto-upgrade. - :vartype throughput_policy: ~azure.mgmt.cosmosdb.models.ThroughputPolicyResource - """ - - _attribute_map = { - "throughput_policy": {"key": "throughputPolicy", "type": "ThroughputPolicyResource"}, - } - - def __init__( - self, *, throughput_policy: Optional["_models.ThroughputPolicyResource"] = None, **kwargs: Any - ) -> None: - """ - :keyword throughput_policy: Represents throughput policy which service must adhere to for - auto-upgrade. - :paramtype throughput_policy: ~azure.mgmt.cosmosdb.models.ThroughputPolicyResource - """ - super().__init__(**kwargs) - self.throughput_policy = throughput_policy - - -class DataTransferDataSourceSink(_serialization.Model): - """Base class for all DataTransfer source/sink. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - AzureBlobDataTransferDataSourceSink, BaseCosmosDataTransferDataSourceSink, - CosmosMongoVCoreDataTransferDataSourceSink - - All required parameters must be populated in order to send to server. - - :ivar component: Known values are: "CosmosDBCassandra", "CosmosDBMongo", "CosmosDBMongoVCore", - "CosmosDBSql", and "AzureBlobStorage". - :vartype component: str or ~azure.mgmt.cosmosdb.models.DataTransferComponent - """ - - _validation = { - "component": {"required": True}, - } - - _attribute_map = { - "component": {"key": "component", "type": "str"}, - } - - _subtype_map = { - "component": { - "AzureBlobStorage": "AzureBlobDataTransferDataSourceSink", - "BaseCosmosDataTransferDataSourceSink": "BaseCosmosDataTransferDataSourceSink", - "CosmosDBMongoVCore": "CosmosMongoVCoreDataTransferDataSourceSink", - } - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.component: Optional[str] = None - - -class AzureBlobDataTransferDataSourceSink(DataTransferDataSourceSink): - """An Azure Blob Storage data source/sink. - - All required parameters must be populated in order to send to server. - - :ivar component: Known values are: "CosmosDBCassandra", "CosmosDBMongo", "CosmosDBMongoVCore", - "CosmosDBSql", and "AzureBlobStorage". - :vartype component: str or ~azure.mgmt.cosmosdb.models.DataTransferComponent - :ivar container_name: Required. - :vartype container_name: str - :ivar endpoint_url: - :vartype endpoint_url: str - """ - - _validation = { - "component": {"required": True}, - "container_name": {"required": True}, - } - - _attribute_map = { - "component": {"key": "component", "type": "str"}, - "container_name": {"key": "containerName", "type": "str"}, - "endpoint_url": {"key": "endpointUrl", "type": "str"}, - } - - def __init__(self, *, container_name: str, endpoint_url: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword container_name: Required. - :paramtype container_name: str - :keyword endpoint_url: - :paramtype endpoint_url: str - """ - super().__init__(**kwargs) - self.component: str = "AzureBlobStorage" - self.container_name = container_name - self.endpoint_url = endpoint_url - - -class BackupInformation(_serialization.Model): - """Backup information of a resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar continuous_backup_information: Information about the status of continuous backups. - :vartype continuous_backup_information: ~azure.mgmt.cosmosdb.models.ContinuousBackupInformation - """ - - _validation = { - "continuous_backup_information": {"readonly": True}, - } - - _attribute_map = { - "continuous_backup_information": {"key": "continuousBackupInformation", "type": "ContinuousBackupInformation"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.continuous_backup_information = None - - -class BackupPolicy(_serialization.Model): - """The object representing the policy for taking backups on an account. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - ContinuousModeBackupPolicy, PeriodicModeBackupPolicy - - All required parameters must be populated in order to send to server. - - :ivar type: Describes the mode of backups. Required. Known values are: "Periodic" and - "Continuous". - :vartype type: str or ~azure.mgmt.cosmosdb.models.BackupPolicyType - :ivar migration_state: The object representing the state of the migration between the backup - policies. - :vartype migration_state: ~azure.mgmt.cosmosdb.models.BackupPolicyMigrationState - """ - - _validation = { - "type": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "migration_state": {"key": "migrationState", "type": "BackupPolicyMigrationState"}, - } - - _subtype_map = {"type": {"Continuous": "ContinuousModeBackupPolicy", "Periodic": "PeriodicModeBackupPolicy"}} - - def __init__( - self, *, migration_state: Optional["_models.BackupPolicyMigrationState"] = None, **kwargs: Any - ) -> None: - """ - :keyword migration_state: The object representing the state of the migration between the backup - policies. - :paramtype migration_state: ~azure.mgmt.cosmosdb.models.BackupPolicyMigrationState - """ - super().__init__(**kwargs) - self.type: Optional[str] = None - self.migration_state = migration_state - - -class BackupPolicyMigrationState(_serialization.Model): - """The object representing the state of the migration between the backup policies. - - :ivar status: Describes the status of migration between backup policy types. Known values are: - "Invalid", "InProgress", "Completed", and "Failed". - :vartype status: str or ~azure.mgmt.cosmosdb.models.BackupPolicyMigrationStatus - :ivar target_type: Describes the target backup policy type of the backup policy migration. - Known values are: "Periodic" and "Continuous". - :vartype target_type: str or ~azure.mgmt.cosmosdb.models.BackupPolicyType - :ivar start_time: Time at which the backup policy migration started (ISO-8601 format). - :vartype start_time: ~datetime.datetime - """ - - _attribute_map = { - "status": {"key": "status", "type": "str"}, - "target_type": {"key": "targetType", "type": "str"}, - "start_time": {"key": "startTime", "type": "iso-8601"}, - } - - def __init__( - self, - *, - status: Optional[Union[str, "_models.BackupPolicyMigrationStatus"]] = None, - target_type: Optional[Union[str, "_models.BackupPolicyType"]] = None, - start_time: Optional[datetime.datetime] = None, - **kwargs: Any - ) -> None: - """ - :keyword status: Describes the status of migration between backup policy types. Known values - are: "Invalid", "InProgress", "Completed", and "Failed". - :paramtype status: str or ~azure.mgmt.cosmosdb.models.BackupPolicyMigrationStatus - :keyword target_type: Describes the target backup policy type of the backup policy migration. - Known values are: "Periodic" and "Continuous". - :paramtype target_type: str or ~azure.mgmt.cosmosdb.models.BackupPolicyType - :keyword start_time: Time at which the backup policy migration started (ISO-8601 format). - :paramtype start_time: ~datetime.datetime - """ - super().__init__(**kwargs) - self.status = status - self.target_type = target_type - self.start_time = start_time - - -class BackupResource(_serialization.Model): - """A restorable backup of a Cassandra cluster. - - :ivar backup_id: The unique identifier of backup. - :vartype backup_id: str - :ivar backup_state: The current state of the backup. Known values are: "Initiated", - "InProgress", "Succeeded", and "Failed". - :vartype backup_state: str or ~azure.mgmt.cosmosdb.models.BackupState - :ivar backup_start_timestamp: The time at which the backup process begins. - :vartype backup_start_timestamp: ~datetime.datetime - :ivar backup_stop_timestamp: The time at which the backup process ends. - :vartype backup_stop_timestamp: ~datetime.datetime - :ivar backup_expiry_timestamp: The time at which the backup will expire. - :vartype backup_expiry_timestamp: ~datetime.datetime - """ - - _attribute_map = { - "backup_id": {"key": "backupId", "type": "str"}, - "backup_state": {"key": "backupState", "type": "str"}, - "backup_start_timestamp": {"key": "backupStartTimestamp", "type": "iso-8601"}, - "backup_stop_timestamp": {"key": "backupStopTimestamp", "type": "iso-8601"}, - "backup_expiry_timestamp": {"key": "backupExpiryTimestamp", "type": "iso-8601"}, - } - - def __init__( - self, - *, - backup_id: Optional[str] = None, - backup_state: Optional[Union[str, "_models.BackupState"]] = None, - backup_start_timestamp: Optional[datetime.datetime] = None, - backup_stop_timestamp: Optional[datetime.datetime] = None, - backup_expiry_timestamp: Optional[datetime.datetime] = None, - **kwargs: Any - ) -> None: - """ - :keyword backup_id: The unique identifier of backup. - :paramtype backup_id: str - :keyword backup_state: The current state of the backup. Known values are: "Initiated", - "InProgress", "Succeeded", and "Failed". - :paramtype backup_state: str or ~azure.mgmt.cosmosdb.models.BackupState - :keyword backup_start_timestamp: The time at which the backup process begins. - :paramtype backup_start_timestamp: ~datetime.datetime - :keyword backup_stop_timestamp: The time at which the backup process ends. - :paramtype backup_stop_timestamp: ~datetime.datetime - :keyword backup_expiry_timestamp: The time at which the backup will expire. - :paramtype backup_expiry_timestamp: ~datetime.datetime - """ - super().__init__(**kwargs) - self.backup_id = backup_id - self.backup_state = backup_state - self.backup_start_timestamp = backup_start_timestamp - self.backup_stop_timestamp = backup_stop_timestamp - self.backup_expiry_timestamp = backup_expiry_timestamp - - -class BackupSchedule(_serialization.Model): - """BackupSchedule. - - :ivar schedule_name: The unique identifier of backup schedule. - :vartype schedule_name: str - :ivar cron_expression: The cron expression that defines when you want to back up your data. - :vartype cron_expression: str - :ivar retention_in_hours: The retention period (hours) of the backups. If you want to retain - data forever, set retention to 0. - :vartype retention_in_hours: int - """ - - _attribute_map = { - "schedule_name": {"key": "scheduleName", "type": "str"}, - "cron_expression": {"key": "cronExpression", "type": "str"}, - "retention_in_hours": {"key": "retentionInHours", "type": "int"}, - } - - def __init__( - self, - *, - schedule_name: Optional[str] = None, - cron_expression: Optional[str] = None, - retention_in_hours: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword schedule_name: The unique identifier of backup schedule. - :paramtype schedule_name: str - :keyword cron_expression: The cron expression that defines when you want to back up your data. - :paramtype cron_expression: str - :keyword retention_in_hours: The retention period (hours) of the backups. If you want to retain - data forever, set retention to 0. - :paramtype retention_in_hours: int - """ - super().__init__(**kwargs) - self.schedule_name = schedule_name - self.cron_expression = cron_expression - self.retention_in_hours = retention_in_hours - - -class BaseCosmosDataTransferDataSourceSink(DataTransferDataSourceSink): - """A base CosmosDB data source/sink. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - CosmosCassandraDataTransferDataSourceSink, CosmosMongoDataTransferDataSourceSink, - CosmosSqlDataTransferDataSourceSink - - All required parameters must be populated in order to send to server. - - :ivar component: Known values are: "CosmosDBCassandra", "CosmosDBMongo", "CosmosDBMongoVCore", - "CosmosDBSql", and "AzureBlobStorage". - :vartype component: str or ~azure.mgmt.cosmosdb.models.DataTransferComponent - :ivar remote_account_name: - :vartype remote_account_name: str - """ - - _validation = { - "component": {"required": True}, - } - - _attribute_map = { - "component": {"key": "component", "type": "str"}, - "remote_account_name": {"key": "remoteAccountName", "type": "str"}, - } - - _subtype_map = { - "component": { - "CosmosDBCassandra": "CosmosCassandraDataTransferDataSourceSink", - "CosmosDBMongo": "CosmosMongoDataTransferDataSourceSink", - "CosmosDBSql": "CosmosSqlDataTransferDataSourceSink", - } - } - - def __init__(self, *, remote_account_name: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword remote_account_name: - :paramtype remote_account_name: str - """ - super().__init__(**kwargs) - self.component: str = "BaseCosmosDataTransferDataSourceSink" - self.remote_account_name = remote_account_name - - -class Capability(_serialization.Model): - """Cosmos DB capability object. - - :ivar name: Name of the Cosmos DB capability. For example, "name": "EnableCassandra". Current - values also include "EnableTable" and "EnableGremlin". - :vartype name: str - """ - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - } - - def __init__(self, *, name: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword name: Name of the Cosmos DB capability. For example, "name": "EnableCassandra". - Current values also include "EnableTable" and "EnableGremlin". - :paramtype name: str - """ - super().__init__(**kwargs) - self.name = name - - -class Capacity(_serialization.Model): - """The object that represents all properties related to capacity enforcement on an account. - - :ivar total_throughput_limit: The total throughput limit imposed on the account. A - totalThroughputLimit of 2000 imposes a strict limit of max throughput that can be provisioned - on that account to be 2000. A totalThroughputLimit of -1 indicates no limits on provisioning of - throughput. - :vartype total_throughput_limit: int - """ - - _validation = { - "total_throughput_limit": {"minimum": -1}, - } - - _attribute_map = { - "total_throughput_limit": {"key": "totalThroughputLimit", "type": "int"}, - } - - def __init__(self, *, total_throughput_limit: Optional[int] = None, **kwargs: Any) -> None: - """ - :keyword total_throughput_limit: The total throughput limit imposed on the account. A - totalThroughputLimit of 2000 imposes a strict limit of max throughput that can be provisioned - on that account to be 2000. A totalThroughputLimit of -1 indicates no limits on provisioning of - throughput. - :paramtype total_throughput_limit: int - """ - super().__init__(**kwargs) - self.total_throughput_limit = total_throughput_limit - - -class CapacityModeChangeTransitionState(_serialization.Model): - """The transition state information related capacity mode change with update request. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar capacity_mode_transition_status: The transition status of capacity mode. Known values - are: "Invalid", "Initialized", "InProgress", "Completed", and "Failed". - :vartype capacity_mode_transition_status: str or - ~azure.mgmt.cosmosdb.models.CapacityModeTransitionStatus - :ivar current_capacity_mode: Indicates the current capacity mode of the account. Known values - are: "None", "Provisioned", and "Serverless". - :vartype current_capacity_mode: str or ~azure.mgmt.cosmosdb.models.CapacityMode - :ivar previous_capacity_mode: Indicates the previous capacity mode of the account before - successful transition. Known values are: "None", "Provisioned", and "Serverless". - :vartype previous_capacity_mode: str or ~azure.mgmt.cosmosdb.models.CapacityMode - :ivar capacity_mode_transition_begin_timestamp: Begin time in UTC of the capacity mode change. - :vartype capacity_mode_transition_begin_timestamp: ~datetime.datetime - :ivar capacity_mode_transition_end_timestamp: End time in UTC of the capacity mode change. - :vartype capacity_mode_transition_end_timestamp: ~datetime.datetime - :ivar capacity_mode_last_successful_transition_end_timestamp: End time in UTC of the last - successful capacity mode change. - :vartype capacity_mode_last_successful_transition_end_timestamp: ~datetime.datetime - """ - - _validation = { - "capacity_mode_transition_begin_timestamp": {"readonly": True}, - "capacity_mode_transition_end_timestamp": {"readonly": True}, - "capacity_mode_last_successful_transition_end_timestamp": {"readonly": True}, - } - - _attribute_map = { - "capacity_mode_transition_status": {"key": "capacityModeTransitionStatus", "type": "str"}, - "current_capacity_mode": {"key": "currentCapacityMode", "type": "str"}, - "previous_capacity_mode": {"key": "previousCapacityMode", "type": "str"}, - "capacity_mode_transition_begin_timestamp": {"key": "capacityModeTransitionBeginTimestamp", "type": "iso-8601"}, - "capacity_mode_transition_end_timestamp": {"key": "capacityModeTransitionEndTimestamp", "type": "iso-8601"}, - "capacity_mode_last_successful_transition_end_timestamp": { - "key": "capacityModeLastSuccessfulTransitionEndTimestamp", - "type": "iso-8601", - }, - } - - def __init__( - self, - *, - capacity_mode_transition_status: Optional[Union[str, "_models.CapacityModeTransitionStatus"]] = None, - current_capacity_mode: Optional[Union[str, "_models.CapacityMode"]] = None, - previous_capacity_mode: Optional[Union[str, "_models.CapacityMode"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword capacity_mode_transition_status: The transition status of capacity mode. Known values - are: "Invalid", "Initialized", "InProgress", "Completed", and "Failed". - :paramtype capacity_mode_transition_status: str or - ~azure.mgmt.cosmosdb.models.CapacityModeTransitionStatus - :keyword current_capacity_mode: Indicates the current capacity mode of the account. Known - values are: "None", "Provisioned", and "Serverless". - :paramtype current_capacity_mode: str or ~azure.mgmt.cosmosdb.models.CapacityMode - :keyword previous_capacity_mode: Indicates the previous capacity mode of the account before - successful transition. Known values are: "None", "Provisioned", and "Serverless". - :paramtype previous_capacity_mode: str or ~azure.mgmt.cosmosdb.models.CapacityMode - """ - super().__init__(**kwargs) - self.capacity_mode_transition_status = capacity_mode_transition_status - self.current_capacity_mode = current_capacity_mode - self.previous_capacity_mode = previous_capacity_mode - self.capacity_mode_transition_begin_timestamp = None - self.capacity_mode_transition_end_timestamp = None - self.capacity_mode_last_successful_transition_end_timestamp = None - - -class CassandraClusterDataCenterNodeItem(_serialization.Model): # pylint: disable=too-many-instance-attributes - """CassandraClusterDataCenterNodeItem. - - :ivar address: The node's IP address. - :vartype address: str - :ivar state: The state of the node in Cassandra ring. Known values are: "Normal", "Leaving", - "Joining", "Moving", and "Stopped". - :vartype state: str or ~azure.mgmt.cosmosdb.models.NodeState - :ivar status: - :vartype status: str - :ivar cassandra_process_status: Cassandra service status on this node. - :vartype cassandra_process_status: str - :ivar load: The amount of file system data in the data directory (e.g., 47.66 kB), excluding - all content in the snapshots subdirectories. Because all SSTable data files are included, any - data that is not cleaned up (such as TTL-expired cells or tombstones) is counted. - :vartype load: str - :ivar tokens: List of tokens this node covers. - :vartype tokens: list[str] - :ivar size: - :vartype size: int - :ivar host_id: The network ID of the node. - :vartype host_id: str - :ivar rack: The rack this node is part of. - :vartype rack: str - :ivar timestamp: The timestamp when these statistics were captured. - :vartype timestamp: str - :ivar disk_used_kb: The amount of disk used, in kB, of the directory /var/lib/cassandra. - :vartype disk_used_kb: int - :ivar disk_free_kb: The amount of disk free, in kB, of the directory /var/lib/cassandra. - :vartype disk_free_kb: int - :ivar memory_used_kb: Used memory (calculated as total - free - buffers - cache), in kB. - :vartype memory_used_kb: int - :ivar memory_buffers_and_cached_kb: Memory used by kernel buffers (Buffers in /proc/meminfo) - and page cache and slabs (Cached and SReclaimable in /proc/meminfo), in kB. - :vartype memory_buffers_and_cached_kb: int - :ivar memory_free_kb: Unused memory (MemFree and SwapFree in /proc/meminfo), in kB. - :vartype memory_free_kb: int - :ivar memory_total_kb: Total installed memory (MemTotal and SwapTotal in /proc/meminfo), in kB. - :vartype memory_total_kb: int - :ivar cpu_usage: A float representing the current system-wide CPU utilization as a percentage. - :vartype cpu_usage: float - :ivar is_latest_model: If node has been updated to latest model. - :vartype is_latest_model: bool - """ - - _attribute_map = { - "address": {"key": "address", "type": "str"}, - "state": {"key": "state", "type": "str"}, - "status": {"key": "status", "type": "str"}, - "cassandra_process_status": {"key": "cassandraProcessStatus", "type": "str"}, - "load": {"key": "load", "type": "str"}, - "tokens": {"key": "tokens", "type": "[str]"}, - "size": {"key": "size", "type": "int"}, - "host_id": {"key": "hostID", "type": "str"}, - "rack": {"key": "rack", "type": "str"}, - "timestamp": {"key": "timestamp", "type": "str"}, - "disk_used_kb": {"key": "diskUsedKB", "type": "int"}, - "disk_free_kb": {"key": "diskFreeKB", "type": "int"}, - "memory_used_kb": {"key": "memoryUsedKB", "type": "int"}, - "memory_buffers_and_cached_kb": {"key": "memoryBuffersAndCachedKB", "type": "int"}, - "memory_free_kb": {"key": "memoryFreeKB", "type": "int"}, - "memory_total_kb": {"key": "memoryTotalKB", "type": "int"}, - "cpu_usage": {"key": "cpuUsage", "type": "float"}, - "is_latest_model": {"key": "isLatestModel", "type": "bool"}, - } - - def __init__( - self, - *, - address: Optional[str] = None, - state: Optional[Union[str, "_models.NodeState"]] = None, - status: Optional[str] = None, - cassandra_process_status: Optional[str] = None, - load: Optional[str] = None, - tokens: Optional[List[str]] = None, - size: Optional[int] = None, - host_id: Optional[str] = None, - rack: Optional[str] = None, - timestamp: Optional[str] = None, - disk_used_kb: Optional[int] = None, - disk_free_kb: Optional[int] = None, - memory_used_kb: Optional[int] = None, - memory_buffers_and_cached_kb: Optional[int] = None, - memory_free_kb: Optional[int] = None, - memory_total_kb: Optional[int] = None, - cpu_usage: Optional[float] = None, - is_latest_model: Optional[bool] = None, - **kwargs: Any - ) -> None: - """ - :keyword address: The node's IP address. - :paramtype address: str - :keyword state: The state of the node in Cassandra ring. Known values are: "Normal", "Leaving", - "Joining", "Moving", and "Stopped". - :paramtype state: str or ~azure.mgmt.cosmosdb.models.NodeState - :keyword status: - :paramtype status: str - :keyword cassandra_process_status: Cassandra service status on this node. - :paramtype cassandra_process_status: str - :keyword load: The amount of file system data in the data directory (e.g., 47.66 kB), excluding - all content in the snapshots subdirectories. Because all SSTable data files are included, any - data that is not cleaned up (such as TTL-expired cells or tombstones) is counted. - :paramtype load: str - :keyword tokens: List of tokens this node covers. - :paramtype tokens: list[str] - :keyword size: - :paramtype size: int - :keyword host_id: The network ID of the node. - :paramtype host_id: str - :keyword rack: The rack this node is part of. - :paramtype rack: str - :keyword timestamp: The timestamp when these statistics were captured. - :paramtype timestamp: str - :keyword disk_used_kb: The amount of disk used, in kB, of the directory /var/lib/cassandra. - :paramtype disk_used_kb: int - :keyword disk_free_kb: The amount of disk free, in kB, of the directory /var/lib/cassandra. - :paramtype disk_free_kb: int - :keyword memory_used_kb: Used memory (calculated as total - free - buffers - cache), in kB. - :paramtype memory_used_kb: int - :keyword memory_buffers_and_cached_kb: Memory used by kernel buffers (Buffers in /proc/meminfo) - and page cache and slabs (Cached and SReclaimable in /proc/meminfo), in kB. - :paramtype memory_buffers_and_cached_kb: int - :keyword memory_free_kb: Unused memory (MemFree and SwapFree in /proc/meminfo), in kB. - :paramtype memory_free_kb: int - :keyword memory_total_kb: Total installed memory (MemTotal and SwapTotal in /proc/meminfo), in - kB. - :paramtype memory_total_kb: int - :keyword cpu_usage: A float representing the current system-wide CPU utilization as a - percentage. - :paramtype cpu_usage: float - :keyword is_latest_model: If node has been updated to latest model. - :paramtype is_latest_model: bool - """ - super().__init__(**kwargs) - self.address = address - self.state = state - self.status = status - self.cassandra_process_status = cassandra_process_status - self.load = load - self.tokens = tokens - self.size = size - self.host_id = host_id - self.rack = rack - self.timestamp = timestamp - self.disk_used_kb = disk_used_kb - self.disk_free_kb = disk_free_kb - self.memory_used_kb = memory_used_kb - self.memory_buffers_and_cached_kb = memory_buffers_and_cached_kb - self.memory_free_kb = memory_free_kb - self.memory_total_kb = memory_total_kb - self.cpu_usage = cpu_usage - self.is_latest_model = is_latest_model - - -class CassandraClusterPublicStatus(_serialization.Model): - """Properties of a managed Cassandra cluster public status. - - :ivar e_tag: - :vartype e_tag: str - :ivar reaper_status: - :vartype reaper_status: ~azure.mgmt.cosmosdb.models.ManagedCassandraReaperStatus - :ivar connection_errors: List relevant information about any connection errors to the - Datacenters. - :vartype connection_errors: list[~azure.mgmt.cosmosdb.models.ConnectionError] - :ivar errors: List relevant information about any errors about cluster, data center and - connection error. - :vartype errors: list[~azure.mgmt.cosmosdb.models.CassandraError] - :ivar data_centers: List of the status of each datacenter in this cluster. - :vartype data_centers: - list[~azure.mgmt.cosmosdb.models.CassandraClusterPublicStatusDataCentersItem] - """ - - _attribute_map = { - "e_tag": {"key": "eTag", "type": "str"}, - "reaper_status": {"key": "reaperStatus", "type": "ManagedCassandraReaperStatus"}, - "connection_errors": {"key": "connectionErrors", "type": "[ConnectionError]"}, - "errors": {"key": "errors", "type": "[CassandraError]"}, - "data_centers": {"key": "dataCenters", "type": "[CassandraClusterPublicStatusDataCentersItem]"}, - } - - def __init__( - self, - *, - e_tag: Optional[str] = None, - reaper_status: Optional["_models.ManagedCassandraReaperStatus"] = None, - connection_errors: Optional[List["_models.ConnectionError"]] = None, - errors: Optional[List["_models.CassandraError"]] = None, - data_centers: Optional[List["_models.CassandraClusterPublicStatusDataCentersItem"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword e_tag: - :paramtype e_tag: str - :keyword reaper_status: - :paramtype reaper_status: ~azure.mgmt.cosmosdb.models.ManagedCassandraReaperStatus - :keyword connection_errors: List relevant information about any connection errors to the - Datacenters. - :paramtype connection_errors: list[~azure.mgmt.cosmosdb.models.ConnectionError] - :keyword errors: List relevant information about any errors about cluster, data center and - connection error. - :paramtype errors: list[~azure.mgmt.cosmosdb.models.CassandraError] - :keyword data_centers: List of the status of each datacenter in this cluster. - :paramtype data_centers: - list[~azure.mgmt.cosmosdb.models.CassandraClusterPublicStatusDataCentersItem] - """ - super().__init__(**kwargs) - self.e_tag = e_tag - self.reaper_status = reaper_status - self.connection_errors = connection_errors - self.errors = errors - self.data_centers = data_centers - - -class CassandraClusterPublicStatusDataCentersItem(_serialization.Model): # pylint: disable=name-too-long - """CassandraClusterPublicStatusDataCentersItem. - - :ivar name: The name of this Datacenter. - :vartype name: str - :ivar seed_nodes: A list of all seed nodes in the cluster, managed and unmanaged. - :vartype seed_nodes: list[str] - :ivar nodes: - :vartype nodes: list[~azure.mgmt.cosmosdb.models.CassandraClusterDataCenterNodeItem] - """ - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "seed_nodes": {"key": "seedNodes", "type": "[str]"}, - "nodes": {"key": "nodes", "type": "[CassandraClusterDataCenterNodeItem]"}, - } - - def __init__( - self, - *, - name: Optional[str] = None, - seed_nodes: Optional[List[str]] = None, - nodes: Optional[List["_models.CassandraClusterDataCenterNodeItem"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of this Datacenter. - :paramtype name: str - :keyword seed_nodes: A list of all seed nodes in the cluster, managed and unmanaged. - :paramtype seed_nodes: list[str] - :keyword nodes: - :paramtype nodes: list[~azure.mgmt.cosmosdb.models.CassandraClusterDataCenterNodeItem] - """ - super().__init__(**kwargs) - self.name = name - self.seed_nodes = seed_nodes - self.nodes = nodes - - -class CassandraError(_serialization.Model): - """CassandraError. - - :ivar code: The code of error that occurred. - :vartype code: str - :ivar message: The message of the error. - :vartype message: str - :ivar target: The target resource of the error. - :vartype target: str - :ivar additional_error_info: Additional information about the error. - :vartype additional_error_info: str - """ - - _attribute_map = { - "code": {"key": "code", "type": "str"}, - "message": {"key": "message", "type": "str"}, - "target": {"key": "target", "type": "str"}, - "additional_error_info": {"key": "additionalErrorInfo", "type": "str"}, - } - - def __init__( - self, - *, - code: Optional[str] = None, - message: Optional[str] = None, - target: Optional[str] = None, - additional_error_info: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword code: The code of error that occurred. - :paramtype code: str - :keyword message: The message of the error. - :paramtype message: str - :keyword target: The target resource of the error. - :paramtype target: str - :keyword additional_error_info: Additional information about the error. - :paramtype additional_error_info: str - """ - super().__init__(**kwargs) - self.code = code - self.message = message - self.target = target - self.additional_error_info = additional_error_info - - -class CassandraKeyspaceCreateUpdateParameters(ARMResourceProperties): - """Parameters to create and update Cosmos DB Cassandra keyspace. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: The standard JSON format of a Cassandra keyspace. Required. - :vartype resource: ~azure.mgmt.cosmosdb.models.CassandraKeyspaceResource - :ivar options: A key-value pair of options to be applied for the request. This corresponds to - the headers sent with the request. - :vartype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "resource": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "CassandraKeyspaceResource"}, - "options": {"key": "properties.options", "type": "CreateUpdateOptions"}, - } - - def __init__( - self, - *, - resource: "_models.CassandraKeyspaceResource", - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - options: Optional["_models.CreateUpdateOptions"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: The standard JSON format of a Cassandra keyspace. Required. - :paramtype resource: ~azure.mgmt.cosmosdb.models.CassandraKeyspaceResource - :keyword options: A key-value pair of options to be applied for the request. This corresponds - to the headers sent with the request. - :paramtype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - self.options = options - - -class OptionsResource(_serialization.Model): - """Cosmos DB options resource object. - - :ivar throughput: Value of the Cosmos DB resource throughput or autoscaleSettings. Use the - ThroughputSetting resource when retrieving offer details. - :vartype throughput: int - :ivar autoscale_settings: Specifies the Autoscale settings. - :vartype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettings - """ - - _attribute_map = { - "throughput": {"key": "throughput", "type": "int"}, - "autoscale_settings": {"key": "autoscaleSettings", "type": "AutoscaleSettings"}, - } - - def __init__( - self, - *, - throughput: Optional[int] = None, - autoscale_settings: Optional["_models.AutoscaleSettings"] = None, - **kwargs: Any - ) -> None: - """ - :keyword throughput: Value of the Cosmos DB resource throughput or autoscaleSettings. Use the - ThroughputSetting resource when retrieving offer details. - :paramtype throughput: int - :keyword autoscale_settings: Specifies the Autoscale settings. - :paramtype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettings - """ - super().__init__(**kwargs) - self.throughput = throughput - self.autoscale_settings = autoscale_settings - - -class CassandraKeyspaceGetPropertiesOptions(OptionsResource): - """CassandraKeyspaceGetPropertiesOptions. - - :ivar throughput: Value of the Cosmos DB resource throughput or autoscaleSettings. Use the - ThroughputSetting resource when retrieving offer details. - :vartype throughput: int - :ivar autoscale_settings: Specifies the Autoscale settings. - :vartype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettings - """ - - -class ExtendedResourceProperties(_serialization.Model): - """The system generated resource properties associated with SQL databases, SQL containers, Gremlin - databases and Gremlin graphs. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar rid: A system generated property. A unique identifier. - :vartype rid: str - :ivar ts: A system generated property that denotes the last updated timestamp of the resource. - :vartype ts: float - :ivar etag: A system generated property representing the resource etag required for optimistic - concurrency control. - :vartype etag: str - """ - - _validation = { - "rid": {"readonly": True}, - "ts": {"readonly": True}, - "etag": {"readonly": True}, - } - - _attribute_map = { - "rid": {"key": "_rid", "type": "str"}, - "ts": {"key": "_ts", "type": "float"}, - "etag": {"key": "_etag", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.rid = None - self.ts = None - self.etag = None - - -class CassandraKeyspaceResource(_serialization.Model): - """Cosmos DB Cassandra keyspace resource object. - - All required parameters must be populated in order to send to server. - - :ivar id: Name of the Cosmos DB Cassandra keyspace. Required. - :vartype id: str - """ - - _validation = { - "id": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - } - - def __init__(self, *, id: str, **kwargs: Any) -> None: # pylint: disable=redefined-builtin - """ - :keyword id: Name of the Cosmos DB Cassandra keyspace. Required. - :paramtype id: str - """ - super().__init__(**kwargs) - self.id = id - - -class CassandraKeyspaceGetPropertiesResource(CassandraKeyspaceResource, ExtendedResourceProperties): - """CassandraKeyspaceGetPropertiesResource. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar rid: A system generated property. A unique identifier. - :vartype rid: str - :ivar ts: A system generated property that denotes the last updated timestamp of the resource. - :vartype ts: float - :ivar etag: A system generated property representing the resource etag required for optimistic - concurrency control. - :vartype etag: str - :ivar id: Name of the Cosmos DB Cassandra keyspace. Required. - :vartype id: str - """ - - _validation = { - "rid": {"readonly": True}, - "ts": {"readonly": True}, - "etag": {"readonly": True}, - "id": {"required": True}, - } - - _attribute_map = { - "rid": {"key": "_rid", "type": "str"}, - "ts": {"key": "_ts", "type": "float"}, - "etag": {"key": "_etag", "type": "str"}, - "id": {"key": "id", "type": "str"}, - } - - def __init__(self, *, id: str, **kwargs: Any) -> None: # pylint: disable=redefined-builtin - """ - :keyword id: Name of the Cosmos DB Cassandra keyspace. Required. - :paramtype id: str - """ - super().__init__(id=id, **kwargs) - self.rid = None - self.ts = None - self.etag = None - self.id = id - - -class CassandraKeyspaceGetResults(ARMResourceProperties): - """An Azure Cosmos DB Cassandra keyspace. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: - :vartype resource: ~azure.mgmt.cosmosdb.models.CassandraKeyspaceGetPropertiesResource - :ivar options: - :vartype options: ~azure.mgmt.cosmosdb.models.CassandraKeyspaceGetPropertiesOptions - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "CassandraKeyspaceGetPropertiesResource"}, - "options": {"key": "properties.options", "type": "CassandraKeyspaceGetPropertiesOptions"}, - } - - def __init__( - self, - *, - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - resource: Optional["_models.CassandraKeyspaceGetPropertiesResource"] = None, - options: Optional["_models.CassandraKeyspaceGetPropertiesOptions"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: - :paramtype resource: ~azure.mgmt.cosmosdb.models.CassandraKeyspaceGetPropertiesResource - :keyword options: - :paramtype options: ~azure.mgmt.cosmosdb.models.CassandraKeyspaceGetPropertiesOptions - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - self.options = options - - -class CassandraKeyspaceListResult(_serialization.Model): - """The List operation response, that contains the Cassandra keyspaces and their properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of Cassandra keyspaces and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.CassandraKeyspaceGetResults] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[CassandraKeyspaceGetResults]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class CassandraPartitionKey(_serialization.Model): - """Cosmos DB Cassandra table partition key. - - :ivar name: Name of the Cosmos DB Cassandra table partition key. - :vartype name: str - """ - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - } - - def __init__(self, *, name: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword name: Name of the Cosmos DB Cassandra table partition key. - :paramtype name: str - """ - super().__init__(**kwargs) - self.name = name - - -class CassandraSchema(_serialization.Model): - """Cosmos DB Cassandra table schema. - - :ivar columns: List of Cassandra table columns. - :vartype columns: list[~azure.mgmt.cosmosdb.models.Column] - :ivar partition_keys: List of partition key. - :vartype partition_keys: list[~azure.mgmt.cosmosdb.models.CassandraPartitionKey] - :ivar cluster_keys: List of cluster key. - :vartype cluster_keys: list[~azure.mgmt.cosmosdb.models.ClusterKey] - """ - - _attribute_map = { - "columns": {"key": "columns", "type": "[Column]"}, - "partition_keys": {"key": "partitionKeys", "type": "[CassandraPartitionKey]"}, - "cluster_keys": {"key": "clusterKeys", "type": "[ClusterKey]"}, - } - - def __init__( - self, - *, - columns: Optional[List["_models.Column"]] = None, - partition_keys: Optional[List["_models.CassandraPartitionKey"]] = None, - cluster_keys: Optional[List["_models.ClusterKey"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword columns: List of Cassandra table columns. - :paramtype columns: list[~azure.mgmt.cosmosdb.models.Column] - :keyword partition_keys: List of partition key. - :paramtype partition_keys: list[~azure.mgmt.cosmosdb.models.CassandraPartitionKey] - :keyword cluster_keys: List of cluster key. - :paramtype cluster_keys: list[~azure.mgmt.cosmosdb.models.ClusterKey] - """ - super().__init__(**kwargs) - self.columns = columns - self.partition_keys = partition_keys - self.cluster_keys = cluster_keys - - -class CassandraTableCreateUpdateParameters(ARMResourceProperties): - """Parameters to create and update Cosmos DB Cassandra table. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: The standard JSON format of a Cassandra table. Required. - :vartype resource: ~azure.mgmt.cosmosdb.models.CassandraTableResource - :ivar options: A key-value pair of options to be applied for the request. This corresponds to - the headers sent with the request. - :vartype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "resource": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "CassandraTableResource"}, - "options": {"key": "properties.options", "type": "CreateUpdateOptions"}, - } - - def __init__( - self, - *, - resource: "_models.CassandraTableResource", - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - options: Optional["_models.CreateUpdateOptions"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: The standard JSON format of a Cassandra table. Required. - :paramtype resource: ~azure.mgmt.cosmosdb.models.CassandraTableResource - :keyword options: A key-value pair of options to be applied for the request. This corresponds - to the headers sent with the request. - :paramtype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - self.options = options - - -class CassandraTableGetPropertiesOptions(OptionsResource): - """CassandraTableGetPropertiesOptions. - - :ivar throughput: Value of the Cosmos DB resource throughput or autoscaleSettings. Use the - ThroughputSetting resource when retrieving offer details. - :vartype throughput: int - :ivar autoscale_settings: Specifies the Autoscale settings. - :vartype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettings - """ - - -class CassandraTableResource(_serialization.Model): - """Cosmos DB Cassandra table resource object. - - All required parameters must be populated in order to send to server. - - :ivar id: Name of the Cosmos DB Cassandra table. Required. - :vartype id: str - :ivar default_ttl: Time to live of the Cosmos DB Cassandra table. - :vartype default_ttl: int - :ivar schema: Schema of the Cosmos DB Cassandra table. - :vartype schema: ~azure.mgmt.cosmosdb.models.CassandraSchema - :ivar analytical_storage_ttl: Analytical TTL. - :vartype analytical_storage_ttl: int - """ - - _validation = { - "id": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "default_ttl": {"key": "defaultTtl", "type": "int"}, - "schema": {"key": "schema", "type": "CassandraSchema"}, - "analytical_storage_ttl": {"key": "analyticalStorageTtl", "type": "int"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - default_ttl: Optional[int] = None, - schema: Optional["_models.CassandraSchema"] = None, - analytical_storage_ttl: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: Name of the Cosmos DB Cassandra table. Required. - :paramtype id: str - :keyword default_ttl: Time to live of the Cosmos DB Cassandra table. - :paramtype default_ttl: int - :keyword schema: Schema of the Cosmos DB Cassandra table. - :paramtype schema: ~azure.mgmt.cosmosdb.models.CassandraSchema - :keyword analytical_storage_ttl: Analytical TTL. - :paramtype analytical_storage_ttl: int - """ - super().__init__(**kwargs) - self.id = id - self.default_ttl = default_ttl - self.schema = schema - self.analytical_storage_ttl = analytical_storage_ttl - - -class CassandraTableGetPropertiesResource(CassandraTableResource, ExtendedResourceProperties): - """CassandraTableGetPropertiesResource. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar rid: A system generated property. A unique identifier. - :vartype rid: str - :ivar ts: A system generated property that denotes the last updated timestamp of the resource. - :vartype ts: float - :ivar etag: A system generated property representing the resource etag required for optimistic - concurrency control. - :vartype etag: str - :ivar id: Name of the Cosmos DB Cassandra table. Required. - :vartype id: str - :ivar default_ttl: Time to live of the Cosmos DB Cassandra table. - :vartype default_ttl: int - :ivar schema: Schema of the Cosmos DB Cassandra table. - :vartype schema: ~azure.mgmt.cosmosdb.models.CassandraSchema - :ivar analytical_storage_ttl: Analytical TTL. - :vartype analytical_storage_ttl: int - """ - - _validation = { - "rid": {"readonly": True}, - "ts": {"readonly": True}, - "etag": {"readonly": True}, - "id": {"required": True}, - } - - _attribute_map = { - "rid": {"key": "_rid", "type": "str"}, - "ts": {"key": "_ts", "type": "float"}, - "etag": {"key": "_etag", "type": "str"}, - "id": {"key": "id", "type": "str"}, - "default_ttl": {"key": "defaultTtl", "type": "int"}, - "schema": {"key": "schema", "type": "CassandraSchema"}, - "analytical_storage_ttl": {"key": "analyticalStorageTtl", "type": "int"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - default_ttl: Optional[int] = None, - schema: Optional["_models.CassandraSchema"] = None, - analytical_storage_ttl: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: Name of the Cosmos DB Cassandra table. Required. - :paramtype id: str - :keyword default_ttl: Time to live of the Cosmos DB Cassandra table. - :paramtype default_ttl: int - :keyword schema: Schema of the Cosmos DB Cassandra table. - :paramtype schema: ~azure.mgmt.cosmosdb.models.CassandraSchema - :keyword analytical_storage_ttl: Analytical TTL. - :paramtype analytical_storage_ttl: int - """ - super().__init__( - id=id, default_ttl=default_ttl, schema=schema, analytical_storage_ttl=analytical_storage_ttl, **kwargs - ) - self.rid = None - self.ts = None - self.etag = None - self.id = id - self.default_ttl = default_ttl - self.schema = schema - self.analytical_storage_ttl = analytical_storage_ttl - - -class CassandraTableGetResults(ARMResourceProperties): - """An Azure Cosmos DB Cassandra table. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: - :vartype resource: ~azure.mgmt.cosmosdb.models.CassandraTableGetPropertiesResource - :ivar options: - :vartype options: ~azure.mgmt.cosmosdb.models.CassandraTableGetPropertiesOptions - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "CassandraTableGetPropertiesResource"}, - "options": {"key": "properties.options", "type": "CassandraTableGetPropertiesOptions"}, - } - - def __init__( - self, - *, - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - resource: Optional["_models.CassandraTableGetPropertiesResource"] = None, - options: Optional["_models.CassandraTableGetPropertiesOptions"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: - :paramtype resource: ~azure.mgmt.cosmosdb.models.CassandraTableGetPropertiesResource - :keyword options: - :paramtype options: ~azure.mgmt.cosmosdb.models.CassandraTableGetPropertiesOptions - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - self.options = options - - -class CassandraTableListResult(_serialization.Model): - """The List operation response, that contains the Cassandra tables and their properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of Cassandra tables and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.CassandraTableGetResults] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[CassandraTableGetResults]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class CassandraViewCreateUpdateParameters(ARMResourceProperties): - """Parameters to create and update Cosmos DB Cassandra view. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: The standard JSON format of a Cassandra view. Required. - :vartype resource: ~azure.mgmt.cosmosdb.models.CassandraViewResource - :ivar options: A key-value pair of options to be applied for the request. This corresponds to - the headers sent with the request. - :vartype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "resource": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "CassandraViewResource"}, - "options": {"key": "properties.options", "type": "CreateUpdateOptions"}, - } - - def __init__( - self, - *, - resource: "_models.CassandraViewResource", - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - options: Optional["_models.CreateUpdateOptions"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: The standard JSON format of a Cassandra view. Required. - :paramtype resource: ~azure.mgmt.cosmosdb.models.CassandraViewResource - :keyword options: A key-value pair of options to be applied for the request. This corresponds - to the headers sent with the request. - :paramtype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - self.options = options - - -class CassandraViewGetPropertiesOptions(OptionsResource): - """CassandraViewGetPropertiesOptions. - - :ivar throughput: Value of the Cosmos DB resource throughput or autoscaleSettings. Use the - ThroughputSetting resource when retrieving offer details. - :vartype throughput: int - :ivar autoscale_settings: Specifies the Autoscale settings. - :vartype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettings - """ - - -class CassandraViewResource(_serialization.Model): - """Cosmos DB Cassandra view resource object. - - All required parameters must be populated in order to send to server. - - :ivar id: Name of the Cosmos DB Cassandra view. Required. - :vartype id: str - :ivar view_definition: View Definition of the Cosmos DB Cassandra view. Required. - :vartype view_definition: str - """ - - _validation = { - "id": {"required": True}, - "view_definition": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "view_definition": {"key": "viewDefinition", "type": "str"}, - } - - def __init__(self, *, id: str, view_definition: str, **kwargs: Any) -> None: # pylint: disable=redefined-builtin - """ - :keyword id: Name of the Cosmos DB Cassandra view. Required. - :paramtype id: str - :keyword view_definition: View Definition of the Cosmos DB Cassandra view. Required. - :paramtype view_definition: str - """ - super().__init__(**kwargs) - self.id = id - self.view_definition = view_definition - - -class CassandraViewGetPropertiesResource(CassandraViewResource, ExtendedResourceProperties): - """CassandraViewGetPropertiesResource. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar rid: A system generated property. A unique identifier. - :vartype rid: str - :ivar ts: A system generated property that denotes the last updated timestamp of the resource. - :vartype ts: float - :ivar etag: A system generated property representing the resource etag required for optimistic - concurrency control. - :vartype etag: str - :ivar id: Name of the Cosmos DB Cassandra view. Required. - :vartype id: str - :ivar view_definition: View Definition of the Cosmos DB Cassandra view. Required. - :vartype view_definition: str - """ - - _validation = { - "rid": {"readonly": True}, - "ts": {"readonly": True}, - "etag": {"readonly": True}, - "id": {"required": True}, - "view_definition": {"required": True}, - } - - _attribute_map = { - "rid": {"key": "_rid", "type": "str"}, - "ts": {"key": "_ts", "type": "float"}, - "etag": {"key": "_etag", "type": "str"}, - "id": {"key": "id", "type": "str"}, - "view_definition": {"key": "viewDefinition", "type": "str"}, - } - - def __init__(self, *, id: str, view_definition: str, **kwargs: Any) -> None: # pylint: disable=redefined-builtin - """ - :keyword id: Name of the Cosmos DB Cassandra view. Required. - :paramtype id: str - :keyword view_definition: View Definition of the Cosmos DB Cassandra view. Required. - :paramtype view_definition: str - """ - super().__init__(id=id, view_definition=view_definition, **kwargs) - self.rid = None - self.ts = None - self.etag = None - self.id = id - self.view_definition = view_definition - - -class CassandraViewGetResults(ARMResourceProperties): - """An Azure Cosmos DB Cassandra view. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: - :vartype resource: ~azure.mgmt.cosmosdb.models.CassandraViewGetPropertiesResource - :ivar options: - :vartype options: ~azure.mgmt.cosmosdb.models.CassandraViewGetPropertiesOptions - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "CassandraViewGetPropertiesResource"}, - "options": {"key": "properties.options", "type": "CassandraViewGetPropertiesOptions"}, - } - - def __init__( - self, - *, - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - resource: Optional["_models.CassandraViewGetPropertiesResource"] = None, - options: Optional["_models.CassandraViewGetPropertiesOptions"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: - :paramtype resource: ~azure.mgmt.cosmosdb.models.CassandraViewGetPropertiesResource - :keyword options: - :paramtype options: ~azure.mgmt.cosmosdb.models.CassandraViewGetPropertiesOptions - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - self.options = options - - -class CassandraViewListResult(_serialization.Model): - """The List operation response, that contains the Cassandra views and their properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of Cassandra views and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.CassandraViewGetResults] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[CassandraViewGetResults]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class Certificate(_serialization.Model): - """Certificate. - - :ivar pem: PEM formatted public key. - :vartype pem: str - """ - - _attribute_map = { - "pem": {"key": "pem", "type": "str"}, - } - - def __init__(self, *, pem: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword pem: PEM formatted public key. - :paramtype pem: str - """ - super().__init__(**kwargs) - self.pem = pem - - -class ChaosFaultListResponse(_serialization.Model): - """Chaos Fault List Response. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of Chaos Faults. - :vartype value: list[~azure.mgmt.cosmosdb.models.ChaosFaultResource] - :ivar next_link: The link used to get the next page of results. - :vartype next_link: str - """ - - _validation = { - "value": {"readonly": True}, - "next_link": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[ChaosFaultResource]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - self.next_link = None - - -class Resource(_serialization.Model): - """Common fields that are returned in the response for all Azure Resource Manager resources. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Fully qualified resource ID for the resource. E.g. - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or - "Microsoft.Storage/storageAccounts". - :vartype type: str - :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy - information. - :vartype system_data: ~azure.mgmt.cosmosdb.models.SystemData - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "system_data": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "system_data": {"key": "systemData", "type": "SystemData"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.system_data = None - - -class ProxyResource(Resource): - """The resource model definition for a Azure Resource Manager proxy resource. It will not have - tags and a location. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Fully qualified resource ID for the resource. E.g. - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or - "Microsoft.Storage/storageAccounts". - :vartype type: str - :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy - information. - :vartype system_data: ~azure.mgmt.cosmosdb.models.SystemData - """ - - -class ChaosFaultResource(ProxyResource): - """A request object to enable/disable the chaos fault. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Fully qualified resource ID for the resource. E.g. - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or - "Microsoft.Storage/storageAccounts". - :vartype type: str - :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy - information. - :vartype system_data: ~azure.mgmt.cosmosdb.models.SystemData - :ivar action: Indicates whether what action to take for the Chaos Fault. Known values are: - "Enable" and "Disable". - :vartype action: str or ~azure.mgmt.cosmosdb.models.SupportedActions - :ivar region: Region of the account where the Chaos Fault is to be enabled/disabled. - :vartype region: str - :ivar database_name: Database name. - :vartype database_name: str - :ivar container_name: Container name. - :vartype container_name: str - :ivar provisioning_state: A provisioning state of the Chaos Fault. - :vartype provisioning_state: str - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "system_data": {"readonly": True}, - "provisioning_state": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "system_data": {"key": "systemData", "type": "SystemData"}, - "action": {"key": "properties.action", "type": "str"}, - "region": {"key": "properties.region", "type": "str"}, - "database_name": {"key": "properties.databaseName", "type": "str"}, - "container_name": {"key": "properties.containerName", "type": "str"}, - "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, - } - - def __init__( - self, - *, - action: Optional[Union[str, "_models.SupportedActions"]] = None, - region: Optional[str] = None, - database_name: Optional[str] = None, - container_name: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword action: Indicates whether what action to take for the Chaos Fault. Known values are: - "Enable" and "Disable". - :paramtype action: str or ~azure.mgmt.cosmosdb.models.SupportedActions - :keyword region: Region of the account where the Chaos Fault is to be enabled/disabled. - :paramtype region: str - :keyword database_name: Database name. - :paramtype database_name: str - :keyword container_name: Container name. - :paramtype container_name: str - """ - super().__init__(**kwargs) - self.action = action - self.region = region - self.database_name = database_name - self.container_name = container_name - self.provisioning_state = None - - -class ClientEncryptionIncludedPath(_serialization.Model): - """. - - All required parameters must be populated in order to send to server. - - :ivar path: Path that needs to be encrypted. Required. - :vartype path: str - :ivar client_encryption_key_id: The identifier of the Client Encryption Key to be used to - encrypt the path. Required. - :vartype client_encryption_key_id: str - :ivar encryption_type: The type of encryption to be performed. Eg - Deterministic, Randomized. - Required. - :vartype encryption_type: str - :ivar encryption_algorithm: The encryption algorithm which will be used. Eg - - AEAD_AES_256_CBC_HMAC_SHA256. Required. - :vartype encryption_algorithm: str - """ - - _validation = { - "path": {"required": True}, - "client_encryption_key_id": {"required": True}, - "encryption_type": {"required": True}, - "encryption_algorithm": {"required": True}, - } - - _attribute_map = { - "path": {"key": "path", "type": "str"}, - "client_encryption_key_id": {"key": "clientEncryptionKeyId", "type": "str"}, - "encryption_type": {"key": "encryptionType", "type": "str"}, - "encryption_algorithm": {"key": "encryptionAlgorithm", "type": "str"}, - } - - def __init__( - self, - *, - path: str, - client_encryption_key_id: str, - encryption_type: str, - encryption_algorithm: str, - **kwargs: Any - ) -> None: - """ - :keyword path: Path that needs to be encrypted. Required. - :paramtype path: str - :keyword client_encryption_key_id: The identifier of the Client Encryption Key to be used to - encrypt the path. Required. - :paramtype client_encryption_key_id: str - :keyword encryption_type: The type of encryption to be performed. Eg - Deterministic, - Randomized. Required. - :paramtype encryption_type: str - :keyword encryption_algorithm: The encryption algorithm which will be used. Eg - - AEAD_AES_256_CBC_HMAC_SHA256. Required. - :paramtype encryption_algorithm: str - """ - super().__init__(**kwargs) - self.path = path - self.client_encryption_key_id = client_encryption_key_id - self.encryption_type = encryption_type - self.encryption_algorithm = encryption_algorithm - - -class ClientEncryptionKeyCreateUpdateParameters(_serialization.Model): # pylint: disable=name-too-long - """Parameters to create and update ClientEncryptionKey. - - All required parameters must be populated in order to send to server. - - :ivar resource: The standard JSON format of a ClientEncryptionKey. Required. - :vartype resource: ~azure.mgmt.cosmosdb.models.ClientEncryptionKeyResource - """ - - _validation = { - "resource": {"required": True}, - } - - _attribute_map = { - "resource": {"key": "properties.resource", "type": "ClientEncryptionKeyResource"}, - } - - def __init__(self, *, resource: "_models.ClientEncryptionKeyResource", **kwargs: Any) -> None: - """ - :keyword resource: The standard JSON format of a ClientEncryptionKey. Required. - :paramtype resource: ~azure.mgmt.cosmosdb.models.ClientEncryptionKeyResource - """ - super().__init__(**kwargs) - self.resource = resource - - -class ClientEncryptionKeyResource(_serialization.Model): - """Cosmos DB client encryption key resource object. - - :ivar id: Name of the ClientEncryptionKey. - :vartype id: str - :ivar encryption_algorithm: Encryption algorithm that will be used along with this client - encryption key to encrypt/decrypt data. - :vartype encryption_algorithm: str - :ivar wrapped_data_encryption_key: Wrapped (encrypted) form of the key represented as a byte - array. - :vartype wrapped_data_encryption_key: bytes - :ivar key_wrap_metadata: Metadata for the wrapping provider that can be used to unwrap the - wrapped client encryption key. - :vartype key_wrap_metadata: ~azure.mgmt.cosmosdb.models.KeyWrapMetadata - """ - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "encryption_algorithm": {"key": "encryptionAlgorithm", "type": "str"}, - "wrapped_data_encryption_key": {"key": "wrappedDataEncryptionKey", "type": "bytearray"}, - "key_wrap_metadata": {"key": "keyWrapMetadata", "type": "KeyWrapMetadata"}, - } - - def __init__( - self, - *, - id: Optional[str] = None, # pylint: disable=redefined-builtin - encryption_algorithm: Optional[str] = None, - wrapped_data_encryption_key: Optional[bytes] = None, - key_wrap_metadata: Optional["_models.KeyWrapMetadata"] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: Name of the ClientEncryptionKey. - :paramtype id: str - :keyword encryption_algorithm: Encryption algorithm that will be used along with this client - encryption key to encrypt/decrypt data. - :paramtype encryption_algorithm: str - :keyword wrapped_data_encryption_key: Wrapped (encrypted) form of the key represented as a byte - array. - :paramtype wrapped_data_encryption_key: bytes - :keyword key_wrap_metadata: Metadata for the wrapping provider that can be used to unwrap the - wrapped client encryption key. - :paramtype key_wrap_metadata: ~azure.mgmt.cosmosdb.models.KeyWrapMetadata - """ - super().__init__(**kwargs) - self.id = id - self.encryption_algorithm = encryption_algorithm - self.wrapped_data_encryption_key = wrapped_data_encryption_key - self.key_wrap_metadata = key_wrap_metadata - - -class ClientEncryptionKeyGetPropertiesResource(ClientEncryptionKeyResource, ExtendedResourceProperties): - """ClientEncryptionKeyGetPropertiesResource. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar rid: A system generated property. A unique identifier. - :vartype rid: str - :ivar ts: A system generated property that denotes the last updated timestamp of the resource. - :vartype ts: float - :ivar etag: A system generated property representing the resource etag required for optimistic - concurrency control. - :vartype etag: str - :ivar id: Name of the ClientEncryptionKey. - :vartype id: str - :ivar encryption_algorithm: Encryption algorithm that will be used along with this client - encryption key to encrypt/decrypt data. - :vartype encryption_algorithm: str - :ivar wrapped_data_encryption_key: Wrapped (encrypted) form of the key represented as a byte - array. - :vartype wrapped_data_encryption_key: bytes - :ivar key_wrap_metadata: Metadata for the wrapping provider that can be used to unwrap the - wrapped client encryption key. - :vartype key_wrap_metadata: ~azure.mgmt.cosmosdb.models.KeyWrapMetadata - """ - - _validation = { - "rid": {"readonly": True}, - "ts": {"readonly": True}, - "etag": {"readonly": True}, - } - - _attribute_map = { - "rid": {"key": "_rid", "type": "str"}, - "ts": {"key": "_ts", "type": "float"}, - "etag": {"key": "_etag", "type": "str"}, - "id": {"key": "id", "type": "str"}, - "encryption_algorithm": {"key": "encryptionAlgorithm", "type": "str"}, - "wrapped_data_encryption_key": {"key": "wrappedDataEncryptionKey", "type": "bytearray"}, - "key_wrap_metadata": {"key": "keyWrapMetadata", "type": "KeyWrapMetadata"}, - } - - def __init__( - self, - *, - id: Optional[str] = None, # pylint: disable=redefined-builtin - encryption_algorithm: Optional[str] = None, - wrapped_data_encryption_key: Optional[bytes] = None, - key_wrap_metadata: Optional["_models.KeyWrapMetadata"] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: Name of the ClientEncryptionKey. - :paramtype id: str - :keyword encryption_algorithm: Encryption algorithm that will be used along with this client - encryption key to encrypt/decrypt data. - :paramtype encryption_algorithm: str - :keyword wrapped_data_encryption_key: Wrapped (encrypted) form of the key represented as a byte - array. - :paramtype wrapped_data_encryption_key: bytes - :keyword key_wrap_metadata: Metadata for the wrapping provider that can be used to unwrap the - wrapped client encryption key. - :paramtype key_wrap_metadata: ~azure.mgmt.cosmosdb.models.KeyWrapMetadata - """ - super().__init__( - id=id, - encryption_algorithm=encryption_algorithm, - wrapped_data_encryption_key=wrapped_data_encryption_key, - key_wrap_metadata=key_wrap_metadata, - **kwargs - ) - self.rid = None - self.ts = None - self.etag = None - self.id = id - self.encryption_algorithm = encryption_algorithm - self.wrapped_data_encryption_key = wrapped_data_encryption_key - self.key_wrap_metadata = key_wrap_metadata - - -class ClientEncryptionKeyGetResults(ARMProxyResource): - """Client Encryption Key. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the database account. - :vartype id: str - :ivar name: The name of the database account. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar resource: - :vartype resource: ~azure.mgmt.cosmosdb.models.ClientEncryptionKeyGetPropertiesResource - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "resource": {"key": "properties.resource", "type": "ClientEncryptionKeyGetPropertiesResource"}, - } - - def __init__( - self, *, resource: Optional["_models.ClientEncryptionKeyGetPropertiesResource"] = None, **kwargs: Any - ) -> None: - """ - :keyword resource: - :paramtype resource: ~azure.mgmt.cosmosdb.models.ClientEncryptionKeyGetPropertiesResource - """ - super().__init__(**kwargs) - self.resource = resource - - -class ClientEncryptionKeysListResult(_serialization.Model): - """The List operation response, that contains the client encryption keys and their properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of client encryption keys and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.ClientEncryptionKeyGetResults] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[ClientEncryptionKeyGetResults]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class ClientEncryptionPolicy(_serialization.Model): - """Cosmos DB client encryption policy. - - All required parameters must be populated in order to send to server. - - :ivar included_paths: Paths of the item that need encryption along with path-specific settings. - Required. - :vartype included_paths: list[~azure.mgmt.cosmosdb.models.ClientEncryptionIncludedPath] - :ivar policy_format_version: Version of the client encryption policy definition. Supported - versions are 1 and 2. Version 2 supports id and partition key path encryption. Required. - :vartype policy_format_version: int - """ - - _validation = { - "included_paths": {"required": True}, - "policy_format_version": {"required": True, "maximum": 2, "minimum": 1}, - } - - _attribute_map = { - "included_paths": {"key": "includedPaths", "type": "[ClientEncryptionIncludedPath]"}, - "policy_format_version": {"key": "policyFormatVersion", "type": "int"}, - } - - def __init__( - self, *, included_paths: List["_models.ClientEncryptionIncludedPath"], policy_format_version: int, **kwargs: Any - ) -> None: - """ - :keyword included_paths: Paths of the item that need encryption along with path-specific - settings. Required. - :paramtype included_paths: list[~azure.mgmt.cosmosdb.models.ClientEncryptionIncludedPath] - :keyword policy_format_version: Version of the client encryption policy definition. Supported - versions are 1 and 2. Version 2 supports id and partition key path encryption. Required. - :paramtype policy_format_version: int - """ - super().__init__(**kwargs) - self.included_paths = included_paths - self.policy_format_version = policy_format_version - - -class ClusterKey(_serialization.Model): - """Cosmos DB Cassandra table cluster key. - - :ivar name: Name of the Cosmos DB Cassandra table cluster key. - :vartype name: str - :ivar order_by: Order of the Cosmos DB Cassandra table cluster key, only support "Asc" and - "Desc". - :vartype order_by: str - """ - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "order_by": {"key": "orderBy", "type": "str"}, - } - - def __init__(self, *, name: Optional[str] = None, order_by: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword name: Name of the Cosmos DB Cassandra table cluster key. - :paramtype name: str - :keyword order_by: Order of the Cosmos DB Cassandra table cluster key, only support "Asc" and - "Desc". - :paramtype order_by: str - """ - super().__init__(**kwargs) - self.name = name - self.order_by = order_by - - -class ManagedCassandraARMResourceProperties(_serialization.Model): - """The core properties of ARM resources. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedCassandraManagedServiceIdentity - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedCassandraManagedServiceIdentity"}, - } - - def __init__( - self, - *, - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedCassandraManagedServiceIdentity"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedCassandraManagedServiceIdentity - """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.location = location - self.tags = tags - self.identity = identity - - -class ClusterResource(ManagedCassandraARMResourceProperties): - """Representation of a managed Cassandra cluster. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedCassandraManagedServiceIdentity - :ivar properties: Properties of a managed Cassandra cluster. - :vartype properties: ~azure.mgmt.cosmosdb.models.ClusterResourceProperties - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedCassandraManagedServiceIdentity"}, - "properties": {"key": "properties", "type": "ClusterResourceProperties"}, - } - - def __init__( - self, - *, - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedCassandraManagedServiceIdentity"] = None, - properties: Optional["_models.ClusterResourceProperties"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedCassandraManagedServiceIdentity - :keyword properties: Properties of a managed Cassandra cluster. - :paramtype properties: ~azure.mgmt.cosmosdb.models.ClusterResourceProperties - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.properties = properties - - -class ClusterResourceProperties(_serialization.Model): # pylint: disable=too-many-instance-attributes - """Properties of a managed Cassandra cluster. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar provisioning_state: The status of the resource at the time the operation was called. - Known values are: "Creating", "Updating", "Deleting", "Succeeded", "Failed", and "Canceled". - :vartype provisioning_state: str or - ~azure.mgmt.cosmosdb.models.ManagedCassandraProvisioningState - :ivar restore_from_backup_id: To create an empty cluster, omit this field or set it to null. To - restore a backup into a new cluster, set this field to the resource id of the backup. - :vartype restore_from_backup_id: str - :ivar delegated_management_subnet_id: Resource id of a subnet that this cluster's management - service should have its network interface attached to. The subnet must be routable to all - subnets that will be delegated to data centers. The resource id must be of the form - '/subscriptions/:code:``/resourceGroups/:code:``/providers/Microsoft.Network/virtualNetworks/:code:``/subnets/:code:``'. - :vartype delegated_management_subnet_id: str - :ivar cassandra_version: Which version of Cassandra should this cluster converge to running - (e.g., 3.11). When updated, the cluster may take some time to migrate to the new version. - :vartype cassandra_version: str - :ivar cluster_name_override: If you need to set the clusterName property in cassandra.yaml to - something besides the resource name of the cluster, set the value to use on this property. - :vartype cluster_name_override: str - :ivar authentication_method: Which authentication method Cassandra should use to authenticate - clients. 'None' turns off authentication, so should not be used except in emergencies. - 'Cassandra' is the default password based authentication. The default is 'Cassandra'. Known - values are: "None", "Cassandra", and "Ldap". - :vartype authentication_method: str or ~azure.mgmt.cosmosdb.models.AuthenticationMethod - :ivar initial_cassandra_admin_password: Initial password for clients connecting as admin to the - cluster. Should be changed after cluster creation. Returns null on GET. This field only applies - when the authenticationMethod field is 'Cassandra'. - :vartype initial_cassandra_admin_password: str - :ivar prometheus_endpoint: Hostname or IP address where the Prometheus endpoint containing data - about the managed Cassandra nodes can be reached. - :vartype prometheus_endpoint: ~azure.mgmt.cosmosdb.models.SeedNode - :ivar repair_enabled: Should automatic repairs run on this cluster? If omitted, this is true, - and should stay true unless you are running a hybrid cluster where you are already doing your - own repairs. - :vartype repair_enabled: bool - :ivar auto_replicate: The form of AutoReplicate that is being used by this cluster. Known - values are: "None", "SystemKeyspaces", and "AllKeyspaces". - :vartype auto_replicate: str or ~azure.mgmt.cosmosdb.models.AutoReplicate - :ivar client_certificates: List of TLS certificates used to authorize clients connecting to the - cluster. All connections are TLS encrypted whether clientCertificates is set or not, but if - clientCertificates is set, the managed Cassandra cluster will reject all connections not - bearing a TLS client certificate that can be validated from one or more of the public - certificates in this property. - :vartype client_certificates: list[~azure.mgmt.cosmosdb.models.Certificate] - :ivar external_gossip_certificates: List of TLS certificates used to authorize gossip from - unmanaged data centers. The TLS certificates of all nodes in unmanaged data centers must be - verifiable using one of the certificates provided in this property. - :vartype external_gossip_certificates: list[~azure.mgmt.cosmosdb.models.Certificate] - :ivar gossip_certificates: List of TLS certificates that unmanaged nodes must trust for gossip - with managed nodes. All managed nodes will present TLS client certificates that are verifiable - using one of the certificates provided in this property. - :vartype gossip_certificates: list[~azure.mgmt.cosmosdb.models.Certificate] - :ivar external_seed_nodes: List of IP addresses of seed nodes in unmanaged data centers. These - will be added to the seed node lists of all managed nodes. - :vartype external_seed_nodes: list[~azure.mgmt.cosmosdb.models.SeedNode] - :ivar seed_nodes: List of IP addresses of seed nodes in the managed data centers. These should - be added to the seed node lists of all unmanaged nodes. - :vartype seed_nodes: list[~azure.mgmt.cosmosdb.models.SeedNode] - :ivar external_data_centers: List of the data center names for unmanaged data centers in this - cluster to be included in auto-replication. - :vartype external_data_centers: list[str] - :ivar hours_between_backups: (Deprecated) Number of hours to wait between taking a backup of - the cluster. - :vartype hours_between_backups: int - :ivar deallocated: Whether the cluster and associated data centers has been deallocated. - :vartype deallocated: bool - :ivar cassandra_audit_logging_enabled: Whether Cassandra audit logging is enabled. - :vartype cassandra_audit_logging_enabled: bool - :ivar cluster_type: Type of the cluster. If set to Production, some operations might not be - permitted on cluster. Known values are: "Production" and "NonProduction". - :vartype cluster_type: str or ~azure.mgmt.cosmosdb.models.ClusterType - :ivar provision_error: Error related to resource provisioning. - :vartype provision_error: ~azure.mgmt.cosmosdb.models.CassandraError - :ivar extensions: Extensions to be added or updated on cluster. - :vartype extensions: list[str] - :ivar backup_schedules: List of backup schedules that define when you want to back up your - data. - :vartype backup_schedules: list[~azure.mgmt.cosmosdb.models.BackupSchedule] - :ivar scheduled_event_strategy: How the nodes in the cluster react to scheduled events. Known - values are: "Ignore", "StopAny", and "StopByRack". - :vartype scheduled_event_strategy: str or ~azure.mgmt.cosmosdb.models.ScheduledEventStrategy - :ivar azure_connection_method: How to connect to the azure services needed for running the - cluster. Known values are: "None" and "VPN". - :vartype azure_connection_method: str or ~azure.mgmt.cosmosdb.models.AzureConnectionType - :ivar private_link_resource_id: If the Connection Method is Vpn, this is the Id of the private - link resource that the datacenters need to connect to. - :vartype private_link_resource_id: str - """ - - _validation = { - "gossip_certificates": {"readonly": True}, - "seed_nodes": {"readonly": True}, - "private_link_resource_id": {"readonly": True}, - } - - _attribute_map = { - "provisioning_state": {"key": "provisioningState", "type": "str"}, - "restore_from_backup_id": {"key": "restoreFromBackupId", "type": "str"}, - "delegated_management_subnet_id": {"key": "delegatedManagementSubnetId", "type": "str"}, - "cassandra_version": {"key": "cassandraVersion", "type": "str"}, - "cluster_name_override": {"key": "clusterNameOverride", "type": "str"}, - "authentication_method": {"key": "authenticationMethod", "type": "str"}, - "initial_cassandra_admin_password": {"key": "initialCassandraAdminPassword", "type": "str"}, - "prometheus_endpoint": {"key": "prometheusEndpoint", "type": "SeedNode"}, - "repair_enabled": {"key": "repairEnabled", "type": "bool"}, - "auto_replicate": {"key": "autoReplicate", "type": "str"}, - "client_certificates": {"key": "clientCertificates", "type": "[Certificate]"}, - "external_gossip_certificates": {"key": "externalGossipCertificates", "type": "[Certificate]"}, - "gossip_certificates": {"key": "gossipCertificates", "type": "[Certificate]"}, - "external_seed_nodes": {"key": "externalSeedNodes", "type": "[SeedNode]"}, - "seed_nodes": {"key": "seedNodes", "type": "[SeedNode]"}, - "external_data_centers": {"key": "externalDataCenters", "type": "[str]"}, - "hours_between_backups": {"key": "hoursBetweenBackups", "type": "int"}, - "deallocated": {"key": "deallocated", "type": "bool"}, - "cassandra_audit_logging_enabled": {"key": "cassandraAuditLoggingEnabled", "type": "bool"}, - "cluster_type": {"key": "clusterType", "type": "str"}, - "provision_error": {"key": "provisionError", "type": "CassandraError"}, - "extensions": {"key": "extensions", "type": "[str]"}, - "backup_schedules": {"key": "backupSchedules", "type": "[BackupSchedule]"}, - "scheduled_event_strategy": {"key": "scheduledEventStrategy", "type": "str"}, - "azure_connection_method": {"key": "azureConnectionMethod", "type": "str"}, - "private_link_resource_id": {"key": "privateLinkResourceId", "type": "str"}, - } - - def __init__( # pylint: disable=too-many-locals - self, - *, - provisioning_state: Optional[Union[str, "_models.ManagedCassandraProvisioningState"]] = None, - restore_from_backup_id: Optional[str] = None, - delegated_management_subnet_id: Optional[str] = None, - cassandra_version: Optional[str] = None, - cluster_name_override: Optional[str] = None, - authentication_method: Optional[Union[str, "_models.AuthenticationMethod"]] = None, - initial_cassandra_admin_password: Optional[str] = None, - prometheus_endpoint: Optional["_models.SeedNode"] = None, - repair_enabled: Optional[bool] = None, - auto_replicate: Optional[Union[str, "_models.AutoReplicate"]] = None, - client_certificates: Optional[List["_models.Certificate"]] = None, - external_gossip_certificates: Optional[List["_models.Certificate"]] = None, - external_seed_nodes: Optional[List["_models.SeedNode"]] = None, - external_data_centers: Optional[List[str]] = None, - hours_between_backups: Optional[int] = None, - deallocated: Optional[bool] = None, - cassandra_audit_logging_enabled: Optional[bool] = None, - cluster_type: Optional[Union[str, "_models.ClusterType"]] = None, - provision_error: Optional["_models.CassandraError"] = None, - extensions: Optional[List[str]] = None, - backup_schedules: Optional[List["_models.BackupSchedule"]] = None, - scheduled_event_strategy: Optional[Union[str, "_models.ScheduledEventStrategy"]] = None, - azure_connection_method: Optional[Union[str, "_models.AzureConnectionType"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword provisioning_state: The status of the resource at the time the operation was called. - Known values are: "Creating", "Updating", "Deleting", "Succeeded", "Failed", and "Canceled". - :paramtype provisioning_state: str or - ~azure.mgmt.cosmosdb.models.ManagedCassandraProvisioningState - :keyword restore_from_backup_id: To create an empty cluster, omit this field or set it to null. - To restore a backup into a new cluster, set this field to the resource id of the backup. - :paramtype restore_from_backup_id: str - :keyword delegated_management_subnet_id: Resource id of a subnet that this cluster's management - service should have its network interface attached to. The subnet must be routable to all - subnets that will be delegated to data centers. The resource id must be of the form - '/subscriptions/:code:``/resourceGroups/:code:``/providers/Microsoft.Network/virtualNetworks/:code:``/subnets/:code:``'. - :paramtype delegated_management_subnet_id: str - :keyword cassandra_version: Which version of Cassandra should this cluster converge to running - (e.g., 3.11). When updated, the cluster may take some time to migrate to the new version. - :paramtype cassandra_version: str - :keyword cluster_name_override: If you need to set the clusterName property in cassandra.yaml - to something besides the resource name of the cluster, set the value to use on this property. - :paramtype cluster_name_override: str - :keyword authentication_method: Which authentication method Cassandra should use to - authenticate clients. 'None' turns off authentication, so should not be used except in - emergencies. 'Cassandra' is the default password based authentication. The default is - 'Cassandra'. Known values are: "None", "Cassandra", and "Ldap". - :paramtype authentication_method: str or ~azure.mgmt.cosmosdb.models.AuthenticationMethod - :keyword initial_cassandra_admin_password: Initial password for clients connecting as admin to - the cluster. Should be changed after cluster creation. Returns null on GET. This field only - applies when the authenticationMethod field is 'Cassandra'. - :paramtype initial_cassandra_admin_password: str - :keyword prometheus_endpoint: Hostname or IP address where the Prometheus endpoint containing - data about the managed Cassandra nodes can be reached. - :paramtype prometheus_endpoint: ~azure.mgmt.cosmosdb.models.SeedNode - :keyword repair_enabled: Should automatic repairs run on this cluster? If omitted, this is - true, and should stay true unless you are running a hybrid cluster where you are already doing - your own repairs. - :paramtype repair_enabled: bool - :keyword auto_replicate: The form of AutoReplicate that is being used by this cluster. Known - values are: "None", "SystemKeyspaces", and "AllKeyspaces". - :paramtype auto_replicate: str or ~azure.mgmt.cosmosdb.models.AutoReplicate - :keyword client_certificates: List of TLS certificates used to authorize clients connecting to - the cluster. All connections are TLS encrypted whether clientCertificates is set or not, but if - clientCertificates is set, the managed Cassandra cluster will reject all connections not - bearing a TLS client certificate that can be validated from one or more of the public - certificates in this property. - :paramtype client_certificates: list[~azure.mgmt.cosmosdb.models.Certificate] - :keyword external_gossip_certificates: List of TLS certificates used to authorize gossip from - unmanaged data centers. The TLS certificates of all nodes in unmanaged data centers must be - verifiable using one of the certificates provided in this property. - :paramtype external_gossip_certificates: list[~azure.mgmt.cosmosdb.models.Certificate] - :keyword external_seed_nodes: List of IP addresses of seed nodes in unmanaged data centers. - These will be added to the seed node lists of all managed nodes. - :paramtype external_seed_nodes: list[~azure.mgmt.cosmosdb.models.SeedNode] - :keyword external_data_centers: List of the data center names for unmanaged data centers in - this cluster to be included in auto-replication. - :paramtype external_data_centers: list[str] - :keyword hours_between_backups: (Deprecated) Number of hours to wait between taking a backup of - the cluster. - :paramtype hours_between_backups: int - :keyword deallocated: Whether the cluster and associated data centers has been deallocated. - :paramtype deallocated: bool - :keyword cassandra_audit_logging_enabled: Whether Cassandra audit logging is enabled. - :paramtype cassandra_audit_logging_enabled: bool - :keyword cluster_type: Type of the cluster. If set to Production, some operations might not be - permitted on cluster. Known values are: "Production" and "NonProduction". - :paramtype cluster_type: str or ~azure.mgmt.cosmosdb.models.ClusterType - :keyword provision_error: Error related to resource provisioning. - :paramtype provision_error: ~azure.mgmt.cosmosdb.models.CassandraError - :keyword extensions: Extensions to be added or updated on cluster. - :paramtype extensions: list[str] - :keyword backup_schedules: List of backup schedules that define when you want to back up your - data. - :paramtype backup_schedules: list[~azure.mgmt.cosmosdb.models.BackupSchedule] - :keyword scheduled_event_strategy: How the nodes in the cluster react to scheduled events. - Known values are: "Ignore", "StopAny", and "StopByRack". - :paramtype scheduled_event_strategy: str or ~azure.mgmt.cosmosdb.models.ScheduledEventStrategy - :keyword azure_connection_method: How to connect to the azure services needed for running the - cluster. Known values are: "None" and "VPN". - :paramtype azure_connection_method: str or ~azure.mgmt.cosmosdb.models.AzureConnectionType - """ - super().__init__(**kwargs) - self.provisioning_state = provisioning_state - self.restore_from_backup_id = restore_from_backup_id - self.delegated_management_subnet_id = delegated_management_subnet_id - self.cassandra_version = cassandra_version - self.cluster_name_override = cluster_name_override - self.authentication_method = authentication_method - self.initial_cassandra_admin_password = initial_cassandra_admin_password - self.prometheus_endpoint = prometheus_endpoint - self.repair_enabled = repair_enabled - self.auto_replicate = auto_replicate - self.client_certificates = client_certificates - self.external_gossip_certificates = external_gossip_certificates - self.gossip_certificates = None - self.external_seed_nodes = external_seed_nodes - self.seed_nodes = None - self.external_data_centers = external_data_centers - self.hours_between_backups = hours_between_backups - self.deallocated = deallocated - self.cassandra_audit_logging_enabled = cassandra_audit_logging_enabled - self.cluster_type = cluster_type - self.provision_error = provision_error - self.extensions = extensions - self.backup_schedules = backup_schedules - self.scheduled_event_strategy = scheduled_event_strategy - self.azure_connection_method = azure_connection_method - self.private_link_resource_id = None - - -class Column(_serialization.Model): - """Cosmos DB Cassandra table column. - - :ivar name: Name of the Cosmos DB Cassandra table column. - :vartype name: str - :ivar type: Type of the Cosmos DB Cassandra table column. - :vartype type: str - """ - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - } - - def __init__(self, *, name: Optional[str] = None, type: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword name: Name of the Cosmos DB Cassandra table column. - :paramtype name: str - :keyword type: Type of the Cosmos DB Cassandra table column. - :paramtype type: str - """ - super().__init__(**kwargs) - self.name = name - self.type = type - - -class CommandOutput(_serialization.Model): - """Response of /command api. - - :ivar command_output: Output of the command. - :vartype command_output: str - """ - - _attribute_map = { - "command_output": {"key": "commandOutput", "type": "str"}, - } - - def __init__(self, *, command_output: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword command_output: Output of the command. - :paramtype command_output: str - """ - super().__init__(**kwargs) - self.command_output = command_output - - -class CommandPostBody(_serialization.Model): - """Specification of which command to run where. - - All required parameters must be populated in order to send to server. - - :ivar command: The command which should be run. Required. - :vartype command: str - :ivar arguments: The arguments for the command to be run. - :vartype arguments: JSON - :ivar host: IP address of the cassandra host to run the command on. Required. - :vartype host: str - :ivar cassandra_stop_start: If true, stops cassandra before executing the command and then - start it again. - :vartype cassandra_stop_start: bool - :ivar read_write: If true, allows the command to *write* to the cassandra directory, otherwise - read-only. - :vartype read_write: bool - """ - - _validation = { - "command": {"required": True}, - "host": {"required": True}, - } - - _attribute_map = { - "command": {"key": "command", "type": "str"}, - "arguments": {"key": "arguments", "type": "object"}, - "host": {"key": "host", "type": "str"}, - "cassandra_stop_start": {"key": "cassandra-stop-start", "type": "bool"}, - "read_write": {"key": "readWrite", "type": "bool"}, - } - - def __init__( - self, - *, - command: str, - host: str, - arguments: Optional[JSON] = None, - cassandra_stop_start: Optional[bool] = None, - read_write: Optional[bool] = None, - **kwargs: Any - ) -> None: - """ - :keyword command: The command which should be run. Required. - :paramtype command: str - :keyword arguments: The arguments for the command to be run. - :paramtype arguments: JSON - :keyword host: IP address of the cassandra host to run the command on. Required. - :paramtype host: str - :keyword cassandra_stop_start: If true, stops cassandra before executing the command and then - start it again. - :paramtype cassandra_stop_start: bool - :keyword read_write: If true, allows the command to *write* to the cassandra directory, - otherwise read-only. - :paramtype read_write: bool - """ - super().__init__(**kwargs) - self.command = command - self.arguments = arguments - self.host = host - self.cassandra_stop_start = cassandra_stop_start - self.read_write = read_write - - -class CommandPublicResource(_serialization.Model): - """resource representing a command. - - :ivar command: The command which should be run. - :vartype command: str - :ivar command_id: The unique id of command. - :vartype command_id: str - :ivar arguments: The arguments for the command to be run. - :vartype arguments: JSON - :ivar host: IP address of the cassandra host to run the command on. - :vartype host: str - :ivar is_admin: Whether command has admin privileges. - :vartype is_admin: bool - :ivar cassandra_stop_start: If true, stops cassandra before executing the command and then - start it again. - :vartype cassandra_stop_start: bool - :ivar read_write: If true, allows the command to *write* to the cassandra directory, otherwise - read-only. - :vartype read_write: bool - :ivar result: Result output of the command. - :vartype result: str - :ivar status: Status of the command. Known values are: "Done", "Running", "Enqueue", - "Processing", "Finished", and "Failed". - :vartype status: str or ~azure.mgmt.cosmosdb.models.CommandStatus - :ivar output_file: The name of the file where the result is written. - :vartype output_file: str - """ - - _attribute_map = { - "command": {"key": "command", "type": "str"}, - "command_id": {"key": "commandId", "type": "str"}, - "arguments": {"key": "arguments", "type": "object"}, - "host": {"key": "host", "type": "str"}, - "is_admin": {"key": "isAdmin", "type": "bool"}, - "cassandra_stop_start": {"key": "cassandraStopStart", "type": "bool"}, - "read_write": {"key": "readWrite", "type": "bool"}, - "result": {"key": "result", "type": "str"}, - "status": {"key": "status", "type": "str"}, - "output_file": {"key": "outputFile", "type": "str"}, - } - - def __init__( - self, - *, - command: Optional[str] = None, - command_id: Optional[str] = None, - arguments: Optional[JSON] = None, - host: Optional[str] = None, - is_admin: Optional[bool] = None, - cassandra_stop_start: Optional[bool] = None, - read_write: Optional[bool] = None, - result: Optional[str] = None, - status: Optional[Union[str, "_models.CommandStatus"]] = None, - output_file: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword command: The command which should be run. - :paramtype command: str - :keyword command_id: The unique id of command. - :paramtype command_id: str - :keyword arguments: The arguments for the command to be run. - :paramtype arguments: JSON - :keyword host: IP address of the cassandra host to run the command on. - :paramtype host: str - :keyword is_admin: Whether command has admin privileges. - :paramtype is_admin: bool - :keyword cassandra_stop_start: If true, stops cassandra before executing the command and then - start it again. - :paramtype cassandra_stop_start: bool - :keyword read_write: If true, allows the command to *write* to the cassandra directory, - otherwise read-only. - :paramtype read_write: bool - :keyword result: Result output of the command. - :paramtype result: str - :keyword status: Status of the command. Known values are: "Done", "Running", "Enqueue", - "Processing", "Finished", and "Failed". - :paramtype status: str or ~azure.mgmt.cosmosdb.models.CommandStatus - :keyword output_file: The name of the file where the result is written. - :paramtype output_file: str - """ - super().__init__(**kwargs) - self.command = command - self.command_id = command_id - self.arguments = arguments - self.host = host - self.is_admin = is_admin - self.cassandra_stop_start = cassandra_stop_start - self.read_write = read_write - self.result = result - self.status = status - self.output_file = output_file - - -class CompositePath(_serialization.Model): - """CompositePath. - - :ivar path: The path for which the indexing behavior applies to. Index paths typically start - with root and end with wildcard (/path/*). - :vartype path: str - :ivar order: Sort order for composite paths. Known values are: "ascending" and "descending". - :vartype order: str or ~azure.mgmt.cosmosdb.models.CompositePathSortOrder - """ - - _attribute_map = { - "path": {"key": "path", "type": "str"}, - "order": {"key": "order", "type": "str"}, - } - - def __init__( - self, - *, - path: Optional[str] = None, - order: Optional[Union[str, "_models.CompositePathSortOrder"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword path: The path for which the indexing behavior applies to. Index paths typically start - with root and end with wildcard (/path/*). - :paramtype path: str - :keyword order: Sort order for composite paths. Known values are: "ascending" and "descending". - :paramtype order: str or ~azure.mgmt.cosmosdb.models.CompositePathSortOrder - """ - super().__init__(**kwargs) - self.path = path - self.order = order - - -class ComputedProperty(_serialization.Model): - """The definition of a computed property. - - :ivar name: The name of a computed property, for example - "cp_lowerName". - :vartype name: str - :ivar query: The query that evaluates the value for computed property, for example - "SELECT - VALUE LOWER(c.name) FROM c". - :vartype query: str - """ - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "query": {"key": "query", "type": "str"}, - } - - def __init__(self, *, name: Optional[str] = None, query: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword name: The name of a computed property, for example - "cp_lowerName". - :paramtype name: str - :keyword query: The query that evaluates the value for computed property, for example - "SELECT - VALUE LOWER(c.name) FROM c". - :paramtype query: str - """ - super().__init__(**kwargs) - self.name = name - self.query = query - - -class ConflictResolutionPolicy(_serialization.Model): - """The conflict resolution policy for the container. - - :ivar mode: Indicates the conflict resolution mode. Known values are: "LastWriterWins" and - "Custom". - :vartype mode: str or ~azure.mgmt.cosmosdb.models.ConflictResolutionMode - :ivar conflict_resolution_path: The conflict resolution path in the case of LastWriterWins - mode. - :vartype conflict_resolution_path: str - :ivar conflict_resolution_procedure: The procedure to resolve conflicts in the case of custom - mode. - :vartype conflict_resolution_procedure: str - """ - - _attribute_map = { - "mode": {"key": "mode", "type": "str"}, - "conflict_resolution_path": {"key": "conflictResolutionPath", "type": "str"}, - "conflict_resolution_procedure": {"key": "conflictResolutionProcedure", "type": "str"}, - } - - def __init__( - self, - *, - mode: Union[str, "_models.ConflictResolutionMode"] = "LastWriterWins", - conflict_resolution_path: Optional[str] = None, - conflict_resolution_procedure: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword mode: Indicates the conflict resolution mode. Known values are: "LastWriterWins" and - "Custom". - :paramtype mode: str or ~azure.mgmt.cosmosdb.models.ConflictResolutionMode - :keyword conflict_resolution_path: The conflict resolution path in the case of LastWriterWins - mode. - :paramtype conflict_resolution_path: str - :keyword conflict_resolution_procedure: The procedure to resolve conflicts in the case of - custom mode. - :paramtype conflict_resolution_procedure: str - """ - super().__init__(**kwargs) - self.mode = mode - self.conflict_resolution_path = conflict_resolution_path - self.conflict_resolution_procedure = conflict_resolution_procedure - - -class ConnectionError(_serialization.Model): - """ConnectionError. - - :ivar connection_state: The kind of connection error that occurred. Known values are: - "Unknown", "OK", "OperatorToDataCenterNetworkError", "DatacenterToDatacenterNetworkError", - "InternalOperatorToDataCenterCertificateError", and "InternalError". - :vartype connection_state: str or ~azure.mgmt.cosmosdb.models.ConnectionState - :ivar i_p_from: The IP of host that originated the failed connection. - :vartype i_p_from: str - :ivar i_p_to: The IP that the connection attempted to reach. - :vartype i_p_to: str - :ivar port: The TCP port the connection was attempted on. - :vartype port: int - :ivar exception: Detailed error message about the failed connection. - :vartype exception: str - """ - - _attribute_map = { - "connection_state": {"key": "connectionState", "type": "str"}, - "i_p_from": {"key": "iPFrom", "type": "str"}, - "i_p_to": {"key": "iPTo", "type": "str"}, - "port": {"key": "port", "type": "int"}, - "exception": {"key": "exception", "type": "str"}, - } - - def __init__( - self, - *, - connection_state: Optional[Union[str, "_models.ConnectionState"]] = None, - i_p_from: Optional[str] = None, - i_p_to: Optional[str] = None, - port: Optional[int] = None, - exception: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword connection_state: The kind of connection error that occurred. Known values are: - "Unknown", "OK", "OperatorToDataCenterNetworkError", "DatacenterToDatacenterNetworkError", - "InternalOperatorToDataCenterCertificateError", and "InternalError". - :paramtype connection_state: str or ~azure.mgmt.cosmosdb.models.ConnectionState - :keyword i_p_from: The IP of host that originated the failed connection. - :paramtype i_p_from: str - :keyword i_p_to: The IP that the connection attempted to reach. - :paramtype i_p_to: str - :keyword port: The TCP port the connection was attempted on. - :paramtype port: int - :keyword exception: Detailed error message about the failed connection. - :paramtype exception: str - """ - super().__init__(**kwargs) - self.connection_state = connection_state - self.i_p_from = i_p_from - self.i_p_to = i_p_to - self.port = port - self.exception = exception - - -class ConsistencyPolicy(_serialization.Model): - """The consistency policy for the Cosmos DB database account. - - All required parameters must be populated in order to send to server. - - :ivar default_consistency_level: The default consistency level and configuration settings of - the Cosmos DB account. Required. Known values are: "Eventual", "Session", "BoundedStaleness", - "Strong", and "ConsistentPrefix". - :vartype default_consistency_level: str or ~azure.mgmt.cosmosdb.models.DefaultConsistencyLevel - :ivar max_staleness_prefix: When used with the Bounded Staleness consistency level, this value - represents the number of stale requests tolerated. Accepted range for this value is 1 – - 2,147,483,647. Required when defaultConsistencyPolicy is set to 'BoundedStaleness'. - :vartype max_staleness_prefix: int - :ivar max_interval_in_seconds: When used with the Bounded Staleness consistency level, this - value represents the time amount of staleness (in seconds) tolerated. Accepted range for this - value is 5 - 86400. Required when defaultConsistencyPolicy is set to 'BoundedStaleness'. - :vartype max_interval_in_seconds: int - """ - - _validation = { - "default_consistency_level": {"required": True}, - "max_staleness_prefix": {"maximum": 2147483647, "minimum": 1}, - "max_interval_in_seconds": {"maximum": 86400, "minimum": 5}, - } - - _attribute_map = { - "default_consistency_level": {"key": "defaultConsistencyLevel", "type": "str"}, - "max_staleness_prefix": {"key": "maxStalenessPrefix", "type": "int"}, - "max_interval_in_seconds": {"key": "maxIntervalInSeconds", "type": "int"}, - } - - def __init__( - self, - *, - default_consistency_level: Union[str, "_models.DefaultConsistencyLevel"], - max_staleness_prefix: Optional[int] = None, - max_interval_in_seconds: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword default_consistency_level: The default consistency level and configuration settings of - the Cosmos DB account. Required. Known values are: "Eventual", "Session", "BoundedStaleness", - "Strong", and "ConsistentPrefix". - :paramtype default_consistency_level: str or - ~azure.mgmt.cosmosdb.models.DefaultConsistencyLevel - :keyword max_staleness_prefix: When used with the Bounded Staleness consistency level, this - value represents the number of stale requests tolerated. Accepted range for this value is 1 – - 2,147,483,647. Required when defaultConsistencyPolicy is set to 'BoundedStaleness'. - :paramtype max_staleness_prefix: int - :keyword max_interval_in_seconds: When used with the Bounded Staleness consistency level, this - value represents the time amount of staleness (in seconds) tolerated. Accepted range for this - value is 5 - 86400. Required when defaultConsistencyPolicy is set to 'BoundedStaleness'. - :paramtype max_interval_in_seconds: int - """ - super().__init__(**kwargs) - self.default_consistency_level = default_consistency_level - self.max_staleness_prefix = max_staleness_prefix - self.max_interval_in_seconds = max_interval_in_seconds - - -class ContainerPartitionKey(_serialization.Model): - """The configuration of the partition key to be used for partitioning data into multiple - partitions. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar paths: List of paths using which data within the container can be partitioned. - :vartype paths: list[str] - :ivar kind: Indicates the kind of algorithm used for partitioning. For MultiHash, multiple - partition keys (upto three maximum) are supported for container create. Known values are: - "Hash", "Range", and "MultiHash". - :vartype kind: str or ~azure.mgmt.cosmosdb.models.PartitionKind - :ivar version: Indicates the version of the partition key definition. - :vartype version: int - :ivar system_key: Indicates if the container is using a system generated partition key. - :vartype system_key: bool - """ - - _validation = { - "version": {"maximum": 2, "minimum": 1}, - "system_key": {"readonly": True}, - } - - _attribute_map = { - "paths": {"key": "paths", "type": "[str]"}, - "kind": {"key": "kind", "type": "str"}, - "version": {"key": "version", "type": "int"}, - "system_key": {"key": "systemKey", "type": "bool"}, - } - - def __init__( - self, - *, - paths: Optional[List[str]] = None, - kind: Union[str, "_models.PartitionKind"] = "Hash", - version: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword paths: List of paths using which data within the container can be partitioned. - :paramtype paths: list[str] - :keyword kind: Indicates the kind of algorithm used for partitioning. For MultiHash, multiple - partition keys (upto three maximum) are supported for container create. Known values are: - "Hash", "Range", and "MultiHash". - :paramtype kind: str or ~azure.mgmt.cosmosdb.models.PartitionKind - :keyword version: Indicates the version of the partition key definition. - :paramtype version: int - """ - super().__init__(**kwargs) - self.paths = paths - self.kind = kind - self.version = version - self.system_key = None - - -class ContinuousBackupInformation(_serialization.Model): - """Information about the status of continuous backups. - - :ivar latest_restorable_timestamp: The latest restorable timestamp for a resource. - :vartype latest_restorable_timestamp: str - """ - - _attribute_map = { - "latest_restorable_timestamp": {"key": "latestRestorableTimestamp", "type": "str"}, - } - - def __init__(self, *, latest_restorable_timestamp: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword latest_restorable_timestamp: The latest restorable timestamp for a resource. - :paramtype latest_restorable_timestamp: str - """ - super().__init__(**kwargs) - self.latest_restorable_timestamp = latest_restorable_timestamp - - -class ContinuousBackupRestoreLocation(_serialization.Model): - """Properties of the regional restorable account. - - :ivar location: The name of the continuous backup restore location. - :vartype location: str - """ - - _attribute_map = { - "location": {"key": "location", "type": "str"}, - } - - def __init__(self, *, location: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword location: The name of the continuous backup restore location. - :paramtype location: str - """ - super().__init__(**kwargs) - self.location = location - - -class ContinuousModeBackupPolicy(BackupPolicy): - """The object representing continuous mode backup policy. - - All required parameters must be populated in order to send to server. - - :ivar type: Describes the mode of backups. Required. Known values are: "Periodic" and - "Continuous". - :vartype type: str or ~azure.mgmt.cosmosdb.models.BackupPolicyType - :ivar migration_state: The object representing the state of the migration between the backup - policies. - :vartype migration_state: ~azure.mgmt.cosmosdb.models.BackupPolicyMigrationState - :ivar continuous_mode_properties: Configuration values for continuous mode backup. - :vartype continuous_mode_properties: ~azure.mgmt.cosmosdb.models.ContinuousModeProperties - """ - - _validation = { - "type": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "migration_state": {"key": "migrationState", "type": "BackupPolicyMigrationState"}, - "continuous_mode_properties": {"key": "continuousModeProperties", "type": "ContinuousModeProperties"}, - } - - def __init__( - self, - *, - migration_state: Optional["_models.BackupPolicyMigrationState"] = None, - continuous_mode_properties: Optional["_models.ContinuousModeProperties"] = None, - **kwargs: Any - ) -> None: - """ - :keyword migration_state: The object representing the state of the migration between the backup - policies. - :paramtype migration_state: ~azure.mgmt.cosmosdb.models.BackupPolicyMigrationState - :keyword continuous_mode_properties: Configuration values for continuous mode backup. - :paramtype continuous_mode_properties: ~azure.mgmt.cosmosdb.models.ContinuousModeProperties - """ - super().__init__(migration_state=migration_state, **kwargs) - self.type: str = "Continuous" - self.continuous_mode_properties = continuous_mode_properties - - -class ContinuousModeProperties(_serialization.Model): - """Configuration values for periodic mode backup. - - :ivar tier: Enum to indicate type of Continuos backup mode. Known values are: "Continuous7Days" - and "Continuous30Days". - :vartype tier: str or ~azure.mgmt.cosmosdb.models.ContinuousTier - """ - - _attribute_map = { - "tier": {"key": "tier", "type": "str"}, - } - - def __init__(self, *, tier: Optional[Union[str, "_models.ContinuousTier"]] = None, **kwargs: Any) -> None: - """ - :keyword tier: Enum to indicate type of Continuos backup mode. Known values are: - "Continuous7Days" and "Continuous30Days". - :paramtype tier: str or ~azure.mgmt.cosmosdb.models.ContinuousTier - """ - super().__init__(**kwargs) - self.tier = tier - - -class CorsPolicy(_serialization.Model): - """The CORS policy for the Cosmos DB database account. - - All required parameters must be populated in order to send to server. - - :ivar allowed_origins: The origin domains that are permitted to make a request against the - service via CORS. Required. - :vartype allowed_origins: str - :ivar allowed_methods: The methods (HTTP request verbs) that the origin domain may use for a - CORS request. - :vartype allowed_methods: str - :ivar allowed_headers: The request headers that the origin domain may specify on the CORS - request. - :vartype allowed_headers: str - :ivar exposed_headers: The response headers that may be sent in the response to the CORS - request and exposed by the browser to the request issuer. - :vartype exposed_headers: str - :ivar max_age_in_seconds: The maximum amount time that a browser should cache the preflight - OPTIONS request. - :vartype max_age_in_seconds: int - """ - - _validation = { - "allowed_origins": {"required": True}, - "max_age_in_seconds": {"maximum": 2147483647, "minimum": 1}, - } - - _attribute_map = { - "allowed_origins": {"key": "allowedOrigins", "type": "str"}, - "allowed_methods": {"key": "allowedMethods", "type": "str"}, - "allowed_headers": {"key": "allowedHeaders", "type": "str"}, - "exposed_headers": {"key": "exposedHeaders", "type": "str"}, - "max_age_in_seconds": {"key": "maxAgeInSeconds", "type": "int"}, - } - - def __init__( - self, - *, - allowed_origins: str, - allowed_methods: Optional[str] = None, - allowed_headers: Optional[str] = None, - exposed_headers: Optional[str] = None, - max_age_in_seconds: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword allowed_origins: The origin domains that are permitted to make a request against the - service via CORS. Required. - :paramtype allowed_origins: str - :keyword allowed_methods: The methods (HTTP request verbs) that the origin domain may use for a - CORS request. - :paramtype allowed_methods: str - :keyword allowed_headers: The request headers that the origin domain may specify on the CORS - request. - :paramtype allowed_headers: str - :keyword exposed_headers: The response headers that may be sent in the response to the CORS - request and exposed by the browser to the request issuer. - :paramtype exposed_headers: str - :keyword max_age_in_seconds: The maximum amount time that a browser should cache the preflight - OPTIONS request. - :paramtype max_age_in_seconds: int - """ - super().__init__(**kwargs) - self.allowed_origins = allowed_origins - self.allowed_methods = allowed_methods - self.allowed_headers = allowed_headers - self.exposed_headers = exposed_headers - self.max_age_in_seconds = max_age_in_seconds - - -class CosmosCassandraDataTransferDataSourceSink(BaseCosmosDataTransferDataSourceSink): # pylint: disable=name-too-long - """A CosmosDB Cassandra API data source/sink. - - All required parameters must be populated in order to send to server. - - :ivar component: Known values are: "CosmosDBCassandra", "CosmosDBMongo", "CosmosDBMongoVCore", - "CosmosDBSql", and "AzureBlobStorage". - :vartype component: str or ~azure.mgmt.cosmosdb.models.DataTransferComponent - :ivar remote_account_name: - :vartype remote_account_name: str - :ivar keyspace_name: Required. - :vartype keyspace_name: str - :ivar table_name: Required. - :vartype table_name: str - """ - - _validation = { - "component": {"required": True}, - "keyspace_name": {"required": True}, - "table_name": {"required": True}, - } - - _attribute_map = { - "component": {"key": "component", "type": "str"}, - "remote_account_name": {"key": "remoteAccountName", "type": "str"}, - "keyspace_name": {"key": "keyspaceName", "type": "str"}, - "table_name": {"key": "tableName", "type": "str"}, - } - - def __init__( - self, *, keyspace_name: str, table_name: str, remote_account_name: Optional[str] = None, **kwargs: Any - ) -> None: - """ - :keyword remote_account_name: - :paramtype remote_account_name: str - :keyword keyspace_name: Required. - :paramtype keyspace_name: str - :keyword table_name: Required. - :paramtype table_name: str - """ - super().__init__(remote_account_name=remote_account_name, **kwargs) - self.component: str = "CosmosDBCassandra" - self.keyspace_name = keyspace_name - self.table_name = table_name - - -class CosmosMongoDataTransferDataSourceSink(BaseCosmosDataTransferDataSourceSink): - """A CosmosDB Mongo API data source/sink. - - All required parameters must be populated in order to send to server. - - :ivar component: Known values are: "CosmosDBCassandra", "CosmosDBMongo", "CosmosDBMongoVCore", - "CosmosDBSql", and "AzureBlobStorage". - :vartype component: str or ~azure.mgmt.cosmosdb.models.DataTransferComponent - :ivar remote_account_name: - :vartype remote_account_name: str - :ivar database_name: Required. - :vartype database_name: str - :ivar collection_name: Required. - :vartype collection_name: str - """ - - _validation = { - "component": {"required": True}, - "database_name": {"required": True}, - "collection_name": {"required": True}, - } - - _attribute_map = { - "component": {"key": "component", "type": "str"}, - "remote_account_name": {"key": "remoteAccountName", "type": "str"}, - "database_name": {"key": "databaseName", "type": "str"}, - "collection_name": {"key": "collectionName", "type": "str"}, - } - - def __init__( - self, *, database_name: str, collection_name: str, remote_account_name: Optional[str] = None, **kwargs: Any - ) -> None: - """ - :keyword remote_account_name: - :paramtype remote_account_name: str - :keyword database_name: Required. - :paramtype database_name: str - :keyword collection_name: Required. - :paramtype collection_name: str - """ - super().__init__(remote_account_name=remote_account_name, **kwargs) - self.component: str = "CosmosDBMongo" - self.database_name = database_name - self.collection_name = collection_name - - -class CosmosMongoVCoreDataTransferDataSourceSink(DataTransferDataSourceSink): # pylint: disable=name-too-long - """A CosmosDB Mongo vCore API data source/sink. - - All required parameters must be populated in order to send to server. - - :ivar component: Known values are: "CosmosDBCassandra", "CosmosDBMongo", "CosmosDBMongoVCore", - "CosmosDBSql", and "AzureBlobStorage". - :vartype component: str or ~azure.mgmt.cosmosdb.models.DataTransferComponent - :ivar database_name: Required. - :vartype database_name: str - :ivar collection_name: Required. - :vartype collection_name: str - :ivar host_name: - :vartype host_name: str - :ivar connection_string_key_vault_uri: - :vartype connection_string_key_vault_uri: str - """ - - _validation = { - "component": {"required": True}, - "database_name": {"required": True}, - "collection_name": {"required": True}, - } - - _attribute_map = { - "component": {"key": "component", "type": "str"}, - "database_name": {"key": "databaseName", "type": "str"}, - "collection_name": {"key": "collectionName", "type": "str"}, - "host_name": {"key": "hostName", "type": "str"}, - "connection_string_key_vault_uri": {"key": "connectionStringKeyVaultUri", "type": "str"}, - } - - def __init__( - self, - *, - database_name: str, - collection_name: str, - host_name: Optional[str] = None, - connection_string_key_vault_uri: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword database_name: Required. - :paramtype database_name: str - :keyword collection_name: Required. - :paramtype collection_name: str - :keyword host_name: - :paramtype host_name: str - :keyword connection_string_key_vault_uri: - :paramtype connection_string_key_vault_uri: str - """ - super().__init__(**kwargs) - self.component: str = "CosmosDBMongoVCore" - self.database_name = database_name - self.collection_name = collection_name - self.host_name = host_name - self.connection_string_key_vault_uri = connection_string_key_vault_uri - - -class CosmosSqlDataTransferDataSourceSink(BaseCosmosDataTransferDataSourceSink): - """A CosmosDB No Sql API data source/sink. - - All required parameters must be populated in order to send to server. - - :ivar component: Known values are: "CosmosDBCassandra", "CosmosDBMongo", "CosmosDBMongoVCore", - "CosmosDBSql", and "AzureBlobStorage". - :vartype component: str or ~azure.mgmt.cosmosdb.models.DataTransferComponent - :ivar remote_account_name: - :vartype remote_account_name: str - :ivar database_name: Required. - :vartype database_name: str - :ivar container_name: Required. - :vartype container_name: str - """ - - _validation = { - "component": {"required": True}, - "database_name": {"required": True}, - "container_name": {"required": True}, - } - - _attribute_map = { - "component": {"key": "component", "type": "str"}, - "remote_account_name": {"key": "remoteAccountName", "type": "str"}, - "database_name": {"key": "databaseName", "type": "str"}, - "container_name": {"key": "containerName", "type": "str"}, - } - - def __init__( - self, *, database_name: str, container_name: str, remote_account_name: Optional[str] = None, **kwargs: Any - ) -> None: - """ - :keyword remote_account_name: - :paramtype remote_account_name: str - :keyword database_name: Required. - :paramtype database_name: str - :keyword container_name: Required. - :paramtype container_name: str - """ - super().__init__(remote_account_name=remote_account_name, **kwargs) - self.component: str = "CosmosDBSql" - self.database_name = database_name - self.container_name = container_name - - -class CreateJobRequest(ARMProxyResource): - """Parameters to create Data Transfer Job. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar id: The unique resource identifier of the database account. - :vartype id: str - :ivar name: The name of the database account. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar properties: Data Transfer Create Job Properties. Required. - :vartype properties: ~azure.mgmt.cosmosdb.models.DataTransferJobProperties - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "properties": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "properties": {"key": "properties", "type": "DataTransferJobProperties"}, - } - - def __init__(self, *, properties: "_models.DataTransferJobProperties", **kwargs: Any) -> None: - """ - :keyword properties: Data Transfer Create Job Properties. Required. - :paramtype properties: ~azure.mgmt.cosmosdb.models.DataTransferJobProperties - """ - super().__init__(**kwargs) - self.properties = properties - - -class CreateUpdateOptions(_serialization.Model): - """CreateUpdateOptions are a list of key-value pairs that describe the resource. Supported keys - are "If-Match", "If-None-Match", "Session-Token" and "Throughput". - - :ivar throughput: Request Units per second. For example, "throughput": 10000. - :vartype throughput: int - :ivar autoscale_settings: Specifies the Autoscale settings. Note: Either throughput or - autoscaleSettings is required, but not both. - :vartype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettings - """ - - _attribute_map = { - "throughput": {"key": "throughput", "type": "int"}, - "autoscale_settings": {"key": "autoscaleSettings", "type": "AutoscaleSettings"}, - } - - def __init__( - self, - *, - throughput: Optional[int] = None, - autoscale_settings: Optional["_models.AutoscaleSettings"] = None, - **kwargs: Any - ) -> None: - """ - :keyword throughput: Request Units per second. For example, "throughput": 10000. - :paramtype throughput: int - :keyword autoscale_settings: Specifies the Autoscale settings. Note: Either throughput or - autoscaleSettings is required, but not both. - :paramtype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettings - """ - super().__init__(**kwargs) - self.throughput = throughput - self.autoscale_settings = autoscale_settings - - -class DatabaseAccountConnectionString(_serialization.Model): - """Connection string for the Cosmos DB account. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar connection_string: Value of the connection string. - :vartype connection_string: str - :ivar description: Description of the connection string. - :vartype description: str - :ivar key_kind: Kind of the connection string key. Known values are: "Primary", "Secondary", - "PrimaryReadonly", and "SecondaryReadonly". - :vartype key_kind: str or ~azure.mgmt.cosmosdb.models.Kind - :ivar type: Type of the connection string. Known values are: "Sql", "Table", "MongoDB", - "Cassandra", "CassandraConnectorMetadata", "Gremlin", "SqlDedicatedGateway", "GremlinV2", and - "Undefined". - :vartype type: str or ~azure.mgmt.cosmosdb.models.Type - """ - - _validation = { - "connection_string": {"readonly": True}, - "description": {"readonly": True}, - "key_kind": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "connection_string": {"key": "connectionString", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "key_kind": {"key": "keyKind", "type": "str"}, - "type": {"key": "type", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.connection_string = None - self.description = None - self.key_kind = None - self.type = None - - -class DatabaseAccountCreateUpdateParameters(ARMResourceProperties): # pylint: disable=too-many-instance-attributes - """Parameters to create and update Cosmos DB database accounts. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar kind: Indicates the type of database account. This can only be set at database account - creation. Known values are: "GlobalDocumentDB", "MongoDB", and "Parse". - :vartype kind: str or ~azure.mgmt.cosmosdb.models.DatabaseAccountKind - :ivar consistency_policy: The consistency policy for the Cosmos DB account. - :vartype consistency_policy: ~azure.mgmt.cosmosdb.models.ConsistencyPolicy - :ivar locations: An array that contains the georeplication locations enabled for the Cosmos DB - account. Required. - :vartype locations: list[~azure.mgmt.cosmosdb.models.Location] - :ivar database_account_offer_type: The offer type for the database. Required. Default value is - "Standard". - :vartype database_account_offer_type: str - :ivar ip_rules: List of IpRules. - :vartype ip_rules: list[~azure.mgmt.cosmosdb.models.IpAddressOrRange] - :ivar is_virtual_network_filter_enabled: Flag to indicate whether to enable/disable Virtual - Network ACL rules. - :vartype is_virtual_network_filter_enabled: bool - :ivar enable_automatic_failover: Enables automatic failover of the write region in the rare - event that the region is unavailable due to an outage. Automatic failover will result in a new - write region for the account and is chosen based on the failover priorities configured for the - account. - :vartype enable_automatic_failover: bool - :ivar capabilities: List of Cosmos DB capabilities for the account. - :vartype capabilities: list[~azure.mgmt.cosmosdb.models.Capability] - :ivar virtual_network_rules: List of Virtual Network ACL rules configured for the Cosmos DB - account. - :vartype virtual_network_rules: list[~azure.mgmt.cosmosdb.models.VirtualNetworkRule] - :ivar enable_multiple_write_locations: Enables the account to write in multiple locations. - :vartype enable_multiple_write_locations: bool - :ivar enable_cassandra_connector: Enables the cassandra connector on the Cosmos DB C* account. - :vartype enable_cassandra_connector: bool - :ivar connector_offer: The cassandra connector offer type for the Cosmos DB database C* - account. "Small" - :vartype connector_offer: str or ~azure.mgmt.cosmosdb.models.ConnectorOffer - :ivar disable_key_based_metadata_write_access: Disable write operations on metadata resources - (databases, containers, throughput) via account keys. - :vartype disable_key_based_metadata_write_access: bool - :ivar key_vault_key_uri: The URI of the key vault. - :vartype key_vault_key_uri: str - :ivar default_identity: The default identity for accessing key vault used in features like - customer managed keys. The default identity needs to be explicitly set by the users. It can be - "FirstPartyIdentity", "SystemAssignedIdentity" and more. - :vartype default_identity: str - :ivar public_network_access: Whether requests from Public Network are allowed. Known values - are: "Enabled", "Disabled", and "SecuredByPerimeter". - :vartype public_network_access: str or ~azure.mgmt.cosmosdb.models.PublicNetworkAccess - :ivar enable_free_tier: Flag to indicate whether Free Tier is enabled. - :vartype enable_free_tier: bool - :ivar api_properties: API specific properties. Currently, supported only for MongoDB API. - :vartype api_properties: ~azure.mgmt.cosmosdb.models.ApiProperties - :ivar enable_analytical_storage: Flag to indicate whether to enable storage analytics. - :vartype enable_analytical_storage: bool - :ivar analytical_storage_configuration: Analytical storage specific properties. - :vartype analytical_storage_configuration: - ~azure.mgmt.cosmosdb.models.AnalyticalStorageConfiguration - :ivar create_mode: Enum to indicate the mode of account creation. Known values are: "Default" - and "Restore". - :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - :ivar backup_policy: The object representing the policy for taking backups on an account. - :vartype backup_policy: ~azure.mgmt.cosmosdb.models.BackupPolicy - :ivar cors: The CORS policy for the Cosmos DB database account. - :vartype cors: list[~azure.mgmt.cosmosdb.models.CorsPolicy] - :ivar network_acl_bypass: Indicates what services are allowed to bypass firewall checks. Known - values are: "None" and "AzureServices". - :vartype network_acl_bypass: str or ~azure.mgmt.cosmosdb.models.NetworkAclBypass - :ivar network_acl_bypass_resource_ids: An array that contains the Resource Ids for Network Acl - Bypass for the Cosmos DB account. - :vartype network_acl_bypass_resource_ids: list[str] - :ivar diagnostic_log_settings: The Object representing the different Diagnostic log settings - for the Cosmos DB Account. - :vartype diagnostic_log_settings: ~azure.mgmt.cosmosdb.models.DiagnosticLogSettings - :ivar disable_local_auth: Opt-out of local authentication and ensure only MSI and AAD can be - used exclusively for authentication. - :vartype disable_local_auth: bool - :ivar restore_parameters: Parameters to indicate the information about the restore. - :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.RestoreParameters - :ivar capacity: The object that represents all properties related to capacity enforcement on an - account. - :vartype capacity: ~azure.mgmt.cosmosdb.models.Capacity - :ivar capacity_mode: Indicates the capacityMode of the Cosmos DB account. Known values are: - "None", "Provisioned", and "Serverless". - :vartype capacity_mode: str or ~azure.mgmt.cosmosdb.models.CapacityMode - :ivar enable_materialized_views: Flag to indicate whether to enable MaterializedViews on the - Cosmos DB account. - :vartype enable_materialized_views: bool - :ivar keys_metadata: This property is ignored during the update/create operation, as the - metadata is read-only. The object represents the metadata for the Account Keys of the Cosmos DB - account. - :vartype keys_metadata: ~azure.mgmt.cosmosdb.models.DatabaseAccountKeysMetadata - :ivar enable_partition_merge: Flag to indicate enabling/disabling of Partition Merge feature on - the account. - :vartype enable_partition_merge: bool - :ivar enable_burst_capacity: Flag to indicate enabling/disabling of Burst Capacity Preview - feature on the account. - :vartype enable_burst_capacity: bool - :ivar minimal_tls_version: Indicates the minimum allowed Tls version. The default is Tls 1.0, - except for Cassandra and Mongo API's, which only work with Tls 1.2. Known values are: "Tls", - "Tls11", and "Tls12". - :vartype minimal_tls_version: str or ~azure.mgmt.cosmosdb.models.MinimalTlsVersion - :ivar customer_managed_key_status: Indicates the status of the Customer Managed Key feature on - the account. In case there are errors, the property provides troubleshooting guidance. - :vartype customer_managed_key_status: str - :ivar enable_priority_based_execution: Flag to indicate enabling/disabling of Priority Based - Execution Preview feature on the account. - :vartype enable_priority_based_execution: bool - :ivar default_priority_level: Enum to indicate default Priority Level of request for Priority - Based Execution. Known values are: "High" and "Low". - :vartype default_priority_level: str or ~azure.mgmt.cosmosdb.models.DefaultPriorityLevel - :ivar enable_per_region_per_partition_autoscale: Flag to indicate enabling/disabling of - Per-Region Per-partition autoscale Preview feature on the account. - :vartype enable_per_region_per_partition_autoscale: bool - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "locations": {"required": True}, - "database_account_offer_type": {"required": True, "constant": True}, - "keys_metadata": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "kind": {"key": "kind", "type": "str"}, - "consistency_policy": {"key": "properties.consistencyPolicy", "type": "ConsistencyPolicy"}, - "locations": {"key": "properties.locations", "type": "[Location]"}, - "database_account_offer_type": {"key": "properties.databaseAccountOfferType", "type": "str"}, - "ip_rules": {"key": "properties.ipRules", "type": "[IpAddressOrRange]"}, - "is_virtual_network_filter_enabled": {"key": "properties.isVirtualNetworkFilterEnabled", "type": "bool"}, - "enable_automatic_failover": {"key": "properties.enableAutomaticFailover", "type": "bool"}, - "capabilities": {"key": "properties.capabilities", "type": "[Capability]"}, - "virtual_network_rules": {"key": "properties.virtualNetworkRules", "type": "[VirtualNetworkRule]"}, - "enable_multiple_write_locations": {"key": "properties.enableMultipleWriteLocations", "type": "bool"}, - "enable_cassandra_connector": {"key": "properties.enableCassandraConnector", "type": "bool"}, - "connector_offer": {"key": "properties.connectorOffer", "type": "str"}, - "disable_key_based_metadata_write_access": { - "key": "properties.disableKeyBasedMetadataWriteAccess", - "type": "bool", - }, - "key_vault_key_uri": {"key": "properties.keyVaultKeyUri", "type": "str"}, - "default_identity": {"key": "properties.defaultIdentity", "type": "str"}, - "public_network_access": {"key": "properties.publicNetworkAccess", "type": "str"}, - "enable_free_tier": {"key": "properties.enableFreeTier", "type": "bool"}, - "api_properties": {"key": "properties.apiProperties", "type": "ApiProperties"}, - "enable_analytical_storage": {"key": "properties.enableAnalyticalStorage", "type": "bool"}, - "analytical_storage_configuration": { - "key": "properties.analyticalStorageConfiguration", - "type": "AnalyticalStorageConfiguration", - }, - "create_mode": {"key": "properties.createMode", "type": "str"}, - "backup_policy": {"key": "properties.backupPolicy", "type": "BackupPolicy"}, - "cors": {"key": "properties.cors", "type": "[CorsPolicy]"}, - "network_acl_bypass": {"key": "properties.networkAclBypass", "type": "str"}, - "network_acl_bypass_resource_ids": {"key": "properties.networkAclBypassResourceIds", "type": "[str]"}, - "diagnostic_log_settings": {"key": "properties.diagnosticLogSettings", "type": "DiagnosticLogSettings"}, - "disable_local_auth": {"key": "properties.disableLocalAuth", "type": "bool"}, - "restore_parameters": {"key": "properties.restoreParameters", "type": "RestoreParameters"}, - "capacity": {"key": "properties.capacity", "type": "Capacity"}, - "capacity_mode": {"key": "properties.capacityMode", "type": "str"}, - "enable_materialized_views": {"key": "properties.enableMaterializedViews", "type": "bool"}, - "keys_metadata": {"key": "properties.keysMetadata", "type": "DatabaseAccountKeysMetadata"}, - "enable_partition_merge": {"key": "properties.enablePartitionMerge", "type": "bool"}, - "enable_burst_capacity": {"key": "properties.enableBurstCapacity", "type": "bool"}, - "minimal_tls_version": {"key": "properties.minimalTlsVersion", "type": "str"}, - "customer_managed_key_status": {"key": "properties.customerManagedKeyStatus", "type": "str"}, - "enable_priority_based_execution": {"key": "properties.enablePriorityBasedExecution", "type": "bool"}, - "default_priority_level": {"key": "properties.defaultPriorityLevel", "type": "str"}, - "enable_per_region_per_partition_autoscale": { - "key": "properties.enablePerRegionPerPartitionAutoscale", - "type": "bool", - }, - } - - database_account_offer_type = "Standard" - - def __init__( # pylint: disable=too-many-locals - self, - *, - locations: List["_models.Location"], - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - kind: Optional[Union[str, "_models.DatabaseAccountKind"]] = None, - consistency_policy: Optional["_models.ConsistencyPolicy"] = None, - ip_rules: Optional[List["_models.IpAddressOrRange"]] = None, - is_virtual_network_filter_enabled: Optional[bool] = None, - enable_automatic_failover: Optional[bool] = None, - capabilities: Optional[List["_models.Capability"]] = None, - virtual_network_rules: Optional[List["_models.VirtualNetworkRule"]] = None, - enable_multiple_write_locations: Optional[bool] = None, - enable_cassandra_connector: Optional[bool] = None, - connector_offer: Optional[Union[str, "_models.ConnectorOffer"]] = None, - disable_key_based_metadata_write_access: Optional[bool] = None, - key_vault_key_uri: Optional[str] = None, - default_identity: Optional[str] = None, - public_network_access: Optional[Union[str, "_models.PublicNetworkAccess"]] = None, - enable_free_tier: Optional[bool] = None, - api_properties: Optional["_models.ApiProperties"] = None, - enable_analytical_storage: Optional[bool] = None, - analytical_storage_configuration: Optional["_models.AnalyticalStorageConfiguration"] = None, - create_mode: Union[str, "_models.CreateMode"] = "Default", - backup_policy: Optional["_models.BackupPolicy"] = None, - cors: Optional[List["_models.CorsPolicy"]] = None, - network_acl_bypass: Optional[Union[str, "_models.NetworkAclBypass"]] = None, - network_acl_bypass_resource_ids: Optional[List[str]] = None, - diagnostic_log_settings: Optional["_models.DiagnosticLogSettings"] = None, - disable_local_auth: Optional[bool] = None, - restore_parameters: Optional["_models.RestoreParameters"] = None, - capacity: Optional["_models.Capacity"] = None, - capacity_mode: Optional[Union[str, "_models.CapacityMode"]] = None, - enable_materialized_views: Optional[bool] = None, - enable_partition_merge: Optional[bool] = None, - enable_burst_capacity: Optional[bool] = None, - minimal_tls_version: Optional[Union[str, "_models.MinimalTlsVersion"]] = None, - customer_managed_key_status: Optional[str] = None, - enable_priority_based_execution: Optional[bool] = None, - default_priority_level: Optional[Union[str, "_models.DefaultPriorityLevel"]] = None, - enable_per_region_per_partition_autoscale: Optional[bool] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword kind: Indicates the type of database account. This can only be set at database account - creation. Known values are: "GlobalDocumentDB", "MongoDB", and "Parse". - :paramtype kind: str or ~azure.mgmt.cosmosdb.models.DatabaseAccountKind - :keyword consistency_policy: The consistency policy for the Cosmos DB account. - :paramtype consistency_policy: ~azure.mgmt.cosmosdb.models.ConsistencyPolicy - :keyword locations: An array that contains the georeplication locations enabled for the Cosmos - DB account. Required. - :paramtype locations: list[~azure.mgmt.cosmosdb.models.Location] - :keyword ip_rules: List of IpRules. - :paramtype ip_rules: list[~azure.mgmt.cosmosdb.models.IpAddressOrRange] - :keyword is_virtual_network_filter_enabled: Flag to indicate whether to enable/disable Virtual - Network ACL rules. - :paramtype is_virtual_network_filter_enabled: bool - :keyword enable_automatic_failover: Enables automatic failover of the write region in the rare - event that the region is unavailable due to an outage. Automatic failover will result in a new - write region for the account and is chosen based on the failover priorities configured for the - account. - :paramtype enable_automatic_failover: bool - :keyword capabilities: List of Cosmos DB capabilities for the account. - :paramtype capabilities: list[~azure.mgmt.cosmosdb.models.Capability] - :keyword virtual_network_rules: List of Virtual Network ACL rules configured for the Cosmos DB - account. - :paramtype virtual_network_rules: list[~azure.mgmt.cosmosdb.models.VirtualNetworkRule] - :keyword enable_multiple_write_locations: Enables the account to write in multiple locations. - :paramtype enable_multiple_write_locations: bool - :keyword enable_cassandra_connector: Enables the cassandra connector on the Cosmos DB C* - account. - :paramtype enable_cassandra_connector: bool - :keyword connector_offer: The cassandra connector offer type for the Cosmos DB database C* - account. "Small" - :paramtype connector_offer: str or ~azure.mgmt.cosmosdb.models.ConnectorOffer - :keyword disable_key_based_metadata_write_access: Disable write operations on metadata - resources (databases, containers, throughput) via account keys. - :paramtype disable_key_based_metadata_write_access: bool - :keyword key_vault_key_uri: The URI of the key vault. - :paramtype key_vault_key_uri: str - :keyword default_identity: The default identity for accessing key vault used in features like - customer managed keys. The default identity needs to be explicitly set by the users. It can be - "FirstPartyIdentity", "SystemAssignedIdentity" and more. - :paramtype default_identity: str - :keyword public_network_access: Whether requests from Public Network are allowed. Known values - are: "Enabled", "Disabled", and "SecuredByPerimeter". - :paramtype public_network_access: str or ~azure.mgmt.cosmosdb.models.PublicNetworkAccess - :keyword enable_free_tier: Flag to indicate whether Free Tier is enabled. - :paramtype enable_free_tier: bool - :keyword api_properties: API specific properties. Currently, supported only for MongoDB API. - :paramtype api_properties: ~azure.mgmt.cosmosdb.models.ApiProperties - :keyword enable_analytical_storage: Flag to indicate whether to enable storage analytics. - :paramtype enable_analytical_storage: bool - :keyword analytical_storage_configuration: Analytical storage specific properties. - :paramtype analytical_storage_configuration: - ~azure.mgmt.cosmosdb.models.AnalyticalStorageConfiguration - :keyword create_mode: Enum to indicate the mode of account creation. Known values are: - "Default" and "Restore". - :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - :keyword backup_policy: The object representing the policy for taking backups on an account. - :paramtype backup_policy: ~azure.mgmt.cosmosdb.models.BackupPolicy - :keyword cors: The CORS policy for the Cosmos DB database account. - :paramtype cors: list[~azure.mgmt.cosmosdb.models.CorsPolicy] - :keyword network_acl_bypass: Indicates what services are allowed to bypass firewall checks. - Known values are: "None" and "AzureServices". - :paramtype network_acl_bypass: str or ~azure.mgmt.cosmosdb.models.NetworkAclBypass - :keyword network_acl_bypass_resource_ids: An array that contains the Resource Ids for Network - Acl Bypass for the Cosmos DB account. - :paramtype network_acl_bypass_resource_ids: list[str] - :keyword diagnostic_log_settings: The Object representing the different Diagnostic log settings - for the Cosmos DB Account. - :paramtype diagnostic_log_settings: ~azure.mgmt.cosmosdb.models.DiagnosticLogSettings - :keyword disable_local_auth: Opt-out of local authentication and ensure only MSI and AAD can be - used exclusively for authentication. - :paramtype disable_local_auth: bool - :keyword restore_parameters: Parameters to indicate the information about the restore. - :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.RestoreParameters - :keyword capacity: The object that represents all properties related to capacity enforcement on - an account. - :paramtype capacity: ~azure.mgmt.cosmosdb.models.Capacity - :keyword capacity_mode: Indicates the capacityMode of the Cosmos DB account. Known values are: - "None", "Provisioned", and "Serverless". - :paramtype capacity_mode: str or ~azure.mgmt.cosmosdb.models.CapacityMode - :keyword enable_materialized_views: Flag to indicate whether to enable MaterializedViews on the - Cosmos DB account. - :paramtype enable_materialized_views: bool - :keyword enable_partition_merge: Flag to indicate enabling/disabling of Partition Merge feature - on the account. - :paramtype enable_partition_merge: bool - :keyword enable_burst_capacity: Flag to indicate enabling/disabling of Burst Capacity Preview - feature on the account. - :paramtype enable_burst_capacity: bool - :keyword minimal_tls_version: Indicates the minimum allowed Tls version. The default is Tls - 1.0, except for Cassandra and Mongo API's, which only work with Tls 1.2. Known values are: - "Tls", "Tls11", and "Tls12". - :paramtype minimal_tls_version: str or ~azure.mgmt.cosmosdb.models.MinimalTlsVersion - :keyword customer_managed_key_status: Indicates the status of the Customer Managed Key feature - on the account. In case there are errors, the property provides troubleshooting guidance. - :paramtype customer_managed_key_status: str - :keyword enable_priority_based_execution: Flag to indicate enabling/disabling of Priority Based - Execution Preview feature on the account. - :paramtype enable_priority_based_execution: bool - :keyword default_priority_level: Enum to indicate default Priority Level of request for - Priority Based Execution. Known values are: "High" and "Low". - :paramtype default_priority_level: str or ~azure.mgmt.cosmosdb.models.DefaultPriorityLevel - :keyword enable_per_region_per_partition_autoscale: Flag to indicate enabling/disabling of - Per-Region Per-partition autoscale Preview feature on the account. - :paramtype enable_per_region_per_partition_autoscale: bool - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.kind = kind - self.consistency_policy = consistency_policy - self.locations = locations - self.ip_rules = ip_rules - self.is_virtual_network_filter_enabled = is_virtual_network_filter_enabled - self.enable_automatic_failover = enable_automatic_failover - self.capabilities = capabilities - self.virtual_network_rules = virtual_network_rules - self.enable_multiple_write_locations = enable_multiple_write_locations - self.enable_cassandra_connector = enable_cassandra_connector - self.connector_offer = connector_offer - self.disable_key_based_metadata_write_access = disable_key_based_metadata_write_access - self.key_vault_key_uri = key_vault_key_uri - self.default_identity = default_identity - self.public_network_access = public_network_access - self.enable_free_tier = enable_free_tier - self.api_properties = api_properties - self.enable_analytical_storage = enable_analytical_storage - self.analytical_storage_configuration = analytical_storage_configuration - self.create_mode = create_mode - self.backup_policy = backup_policy - self.cors = cors - self.network_acl_bypass = network_acl_bypass - self.network_acl_bypass_resource_ids = network_acl_bypass_resource_ids - self.diagnostic_log_settings = diagnostic_log_settings - self.disable_local_auth = disable_local_auth - self.restore_parameters = restore_parameters - self.capacity = capacity - self.capacity_mode = capacity_mode - self.enable_materialized_views = enable_materialized_views - self.keys_metadata = None - self.enable_partition_merge = enable_partition_merge - self.enable_burst_capacity = enable_burst_capacity - self.minimal_tls_version = minimal_tls_version - self.customer_managed_key_status = customer_managed_key_status - self.enable_priority_based_execution = enable_priority_based_execution - self.default_priority_level = default_priority_level - self.enable_per_region_per_partition_autoscale = enable_per_region_per_partition_autoscale - - -class DatabaseAccountGetResults(ARMResourceProperties): # pylint: disable=too-many-instance-attributes - """An Azure Cosmos DB database account. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar kind: Indicates the type of database account. This can only be set at database account - creation. Known values are: "GlobalDocumentDB", "MongoDB", and "Parse". - :vartype kind: str or ~azure.mgmt.cosmosdb.models.DatabaseAccountKind - :ivar system_data: The system meta data relating to this resource. - :vartype system_data: ~azure.mgmt.cosmosdb.models.SystemData - :ivar provisioning_state: The status of the Cosmos DB account at the time the operation was - called. The status can be one of following. 'Creating' – the Cosmos DB account is being - created. When an account is in Creating state, only properties that are specified as input for - the Create Cosmos DB account operation are returned. 'Succeeded' – the Cosmos DB account is - active for use. 'Updating' – the Cosmos DB account is being updated. 'Deleting' – the Cosmos DB - account is being deleted. 'Failed' – the Cosmos DB account failed creation. 'DeletionFailed' – - the Cosmos DB account deletion failed. - :vartype provisioning_state: str - :ivar document_endpoint: The connection endpoint for the Cosmos DB database account. - :vartype document_endpoint: str - :ivar database_account_offer_type: The offer type for the Cosmos DB database account. Default - value: Standard. Default value is "Standard". - :vartype database_account_offer_type: str - :ivar ip_rules: List of IpRules. - :vartype ip_rules: list[~azure.mgmt.cosmosdb.models.IpAddressOrRange] - :ivar is_virtual_network_filter_enabled: Flag to indicate whether to enable/disable Virtual - Network ACL rules. - :vartype is_virtual_network_filter_enabled: bool - :ivar enable_automatic_failover: Enables automatic failover of the write region in the rare - event that the region is unavailable due to an outage. Automatic failover will result in a new - write region for the account and is chosen based on the failover priorities configured for the - account. - :vartype enable_automatic_failover: bool - :ivar consistency_policy: The consistency policy for the Cosmos DB database account. - :vartype consistency_policy: ~azure.mgmt.cosmosdb.models.ConsistencyPolicy - :ivar capabilities: List of Cosmos DB capabilities for the account. - :vartype capabilities: list[~azure.mgmt.cosmosdb.models.Capability] - :ivar write_locations: An array that contains the write location for the Cosmos DB account. - :vartype write_locations: list[~azure.mgmt.cosmosdb.models.Location] - :ivar read_locations: An array that contains of the read locations enabled for the Cosmos DB - account. - :vartype read_locations: list[~azure.mgmt.cosmosdb.models.Location] - :ivar locations: An array that contains all of the locations enabled for the Cosmos DB account. - :vartype locations: list[~azure.mgmt.cosmosdb.models.Location] - :ivar failover_policies: An array that contains the regions ordered by their failover - priorities. - :vartype failover_policies: list[~azure.mgmt.cosmosdb.models.FailoverPolicy] - :ivar virtual_network_rules: List of Virtual Network ACL rules configured for the Cosmos DB - account. - :vartype virtual_network_rules: list[~azure.mgmt.cosmosdb.models.VirtualNetworkRule] - :ivar private_endpoint_connections: List of Private Endpoint Connections configured for the - Cosmos DB account. - :vartype private_endpoint_connections: - list[~azure.mgmt.cosmosdb.models.PrivateEndpointConnection] - :ivar enable_multiple_write_locations: Enables the account to write in multiple locations. - :vartype enable_multiple_write_locations: bool - :ivar enable_cassandra_connector: Enables the cassandra connector on the Cosmos DB C* account. - :vartype enable_cassandra_connector: bool - :ivar connector_offer: The cassandra connector offer type for the Cosmos DB database C* - account. "Small" - :vartype connector_offer: str or ~azure.mgmt.cosmosdb.models.ConnectorOffer - :ivar disable_key_based_metadata_write_access: Disable write operations on metadata resources - (databases, containers, throughput) via account keys. - :vartype disable_key_based_metadata_write_access: bool - :ivar key_vault_key_uri: The URI of the key vault. - :vartype key_vault_key_uri: str - :ivar default_identity: The default identity for accessing key vault used in features like - customer managed keys. The default identity needs to be explicitly set by the users. It can be - "FirstPartyIdentity", "SystemAssignedIdentity" and more. - :vartype default_identity: str - :ivar public_network_access: Whether requests from Public Network are allowed. Known values - are: "Enabled", "Disabled", and "SecuredByPerimeter". - :vartype public_network_access: str or ~azure.mgmt.cosmosdb.models.PublicNetworkAccess - :ivar enable_free_tier: Flag to indicate whether Free Tier is enabled. - :vartype enable_free_tier: bool - :ivar api_properties: API specific properties. - :vartype api_properties: ~azure.mgmt.cosmosdb.models.ApiProperties - :ivar enable_analytical_storage: Flag to indicate whether to enable storage analytics. - :vartype enable_analytical_storage: bool - :ivar analytical_storage_configuration: Analytical storage specific properties. - :vartype analytical_storage_configuration: - ~azure.mgmt.cosmosdb.models.AnalyticalStorageConfiguration - :ivar instance_id: A unique identifier assigned to the database account. - :vartype instance_id: str - :ivar create_mode: Enum to indicate the mode of account creation. Known values are: "Default" - and "Restore". - :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - :ivar restore_parameters: Parameters to indicate the information about the restore. - :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.RestoreParameters - :ivar backup_policy: The object representing the policy for taking backups on an account. - :vartype backup_policy: ~azure.mgmt.cosmosdb.models.BackupPolicy - :ivar cors: The CORS policy for the Cosmos DB database account. - :vartype cors: list[~azure.mgmt.cosmosdb.models.CorsPolicy] - :ivar network_acl_bypass: Indicates what services are allowed to bypass firewall checks. Known - values are: "None" and "AzureServices". - :vartype network_acl_bypass: str or ~azure.mgmt.cosmosdb.models.NetworkAclBypass - :ivar network_acl_bypass_resource_ids: An array that contains the Resource Ids for Network Acl - Bypass for the Cosmos DB account. - :vartype network_acl_bypass_resource_ids: list[str] - :ivar diagnostic_log_settings: The Object representing the different Diagnostic log settings - for the Cosmos DB Account. - :vartype diagnostic_log_settings: ~azure.mgmt.cosmosdb.models.DiagnosticLogSettings - :ivar disable_local_auth: Opt-out of local authentication and ensure only MSI and AAD can be - used exclusively for authentication. - :vartype disable_local_auth: bool - :ivar capacity: The object that represents all properties related to capacity enforcement on an - account. - :vartype capacity: ~azure.mgmt.cosmosdb.models.Capacity - :ivar capacity_mode: Indicates the capacityMode of the Cosmos DB account. Known values are: - "None", "Provisioned", and "Serverless". - :vartype capacity_mode: str or ~azure.mgmt.cosmosdb.models.CapacityMode - :ivar capacity_mode_change_transition_state: The object that represents the migration state for - the CapacityMode of the Cosmos DB account. - :vartype capacity_mode_change_transition_state: - ~azure.mgmt.cosmosdb.models.CapacityModeChangeTransitionState - :ivar enable_materialized_views: Flag to indicate whether to enable MaterializedViews on the - Cosmos DB account. - :vartype enable_materialized_views: bool - :ivar keys_metadata: The object that represents the metadata for the Account Keys of the Cosmos - DB account. - :vartype keys_metadata: ~azure.mgmt.cosmosdb.models.DatabaseAccountKeysMetadata - :ivar enable_partition_merge: Flag to indicate enabling/disabling of Partition Merge feature on - the account. - :vartype enable_partition_merge: bool - :ivar enable_burst_capacity: Flag to indicate enabling/disabling of Burst Capacity Preview - feature on the account. - :vartype enable_burst_capacity: bool - :ivar minimal_tls_version: Indicates the minimum allowed Tls version. The default is Tls 1.0, - except for Cassandra and Mongo API's, which only work with Tls 1.2. Known values are: "Tls", - "Tls11", and "Tls12". - :vartype minimal_tls_version: str or ~azure.mgmt.cosmosdb.models.MinimalTlsVersion - :ivar customer_managed_key_status: Indicates the status of the Customer Managed Key feature on - the account. In case there are errors, the property provides troubleshooting guidance. - :vartype customer_managed_key_status: str - :ivar enable_priority_based_execution: Flag to indicate enabling/disabling of Priority Based - Execution Preview feature on the account. - :vartype enable_priority_based_execution: bool - :ivar default_priority_level: Enum to indicate default Priority Level of request for Priority - Based Execution. Known values are: "High" and "Low". - :vartype default_priority_level: str or ~azure.mgmt.cosmosdb.models.DefaultPriorityLevel - :ivar enable_per_region_per_partition_autoscale: Flag to indicate enabling/disabling of - Per-Region Per-partition autoscale Preview feature on the account. - :vartype enable_per_region_per_partition_autoscale: bool - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "system_data": {"readonly": True}, - "provisioning_state": {"readonly": True}, - "document_endpoint": {"readonly": True}, - "database_account_offer_type": {"readonly": True}, - "write_locations": {"readonly": True}, - "read_locations": {"readonly": True}, - "locations": {"readonly": True}, - "failover_policies": {"readonly": True}, - "private_endpoint_connections": {"readonly": True}, - "instance_id": {"readonly": True}, - "keys_metadata": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "kind": {"key": "kind", "type": "str"}, - "system_data": {"key": "systemData", "type": "SystemData"}, - "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, - "document_endpoint": {"key": "properties.documentEndpoint", "type": "str"}, - "database_account_offer_type": {"key": "properties.databaseAccountOfferType", "type": "str"}, - "ip_rules": {"key": "properties.ipRules", "type": "[IpAddressOrRange]"}, - "is_virtual_network_filter_enabled": {"key": "properties.isVirtualNetworkFilterEnabled", "type": "bool"}, - "enable_automatic_failover": {"key": "properties.enableAutomaticFailover", "type": "bool"}, - "consistency_policy": {"key": "properties.consistencyPolicy", "type": "ConsistencyPolicy"}, - "capabilities": {"key": "properties.capabilities", "type": "[Capability]"}, - "write_locations": {"key": "properties.writeLocations", "type": "[Location]"}, - "read_locations": {"key": "properties.readLocations", "type": "[Location]"}, - "locations": {"key": "properties.locations", "type": "[Location]"}, - "failover_policies": {"key": "properties.failoverPolicies", "type": "[FailoverPolicy]"}, - "virtual_network_rules": {"key": "properties.virtualNetworkRules", "type": "[VirtualNetworkRule]"}, - "private_endpoint_connections": { - "key": "properties.privateEndpointConnections", - "type": "[PrivateEndpointConnection]", - }, - "enable_multiple_write_locations": {"key": "properties.enableMultipleWriteLocations", "type": "bool"}, - "enable_cassandra_connector": {"key": "properties.enableCassandraConnector", "type": "bool"}, - "connector_offer": {"key": "properties.connectorOffer", "type": "str"}, - "disable_key_based_metadata_write_access": { - "key": "properties.disableKeyBasedMetadataWriteAccess", - "type": "bool", - }, - "key_vault_key_uri": {"key": "properties.keyVaultKeyUri", "type": "str"}, - "default_identity": {"key": "properties.defaultIdentity", "type": "str"}, - "public_network_access": {"key": "properties.publicNetworkAccess", "type": "str"}, - "enable_free_tier": {"key": "properties.enableFreeTier", "type": "bool"}, - "api_properties": {"key": "properties.apiProperties", "type": "ApiProperties"}, - "enable_analytical_storage": {"key": "properties.enableAnalyticalStorage", "type": "bool"}, - "analytical_storage_configuration": { - "key": "properties.analyticalStorageConfiguration", - "type": "AnalyticalStorageConfiguration", - }, - "instance_id": {"key": "properties.instanceId", "type": "str"}, - "create_mode": {"key": "properties.createMode", "type": "str"}, - "restore_parameters": {"key": "properties.restoreParameters", "type": "RestoreParameters"}, - "backup_policy": {"key": "properties.backupPolicy", "type": "BackupPolicy"}, - "cors": {"key": "properties.cors", "type": "[CorsPolicy]"}, - "network_acl_bypass": {"key": "properties.networkAclBypass", "type": "str"}, - "network_acl_bypass_resource_ids": {"key": "properties.networkAclBypassResourceIds", "type": "[str]"}, - "diagnostic_log_settings": {"key": "properties.diagnosticLogSettings", "type": "DiagnosticLogSettings"}, - "disable_local_auth": {"key": "properties.disableLocalAuth", "type": "bool"}, - "capacity": {"key": "properties.capacity", "type": "Capacity"}, - "capacity_mode": {"key": "properties.capacityMode", "type": "str"}, - "capacity_mode_change_transition_state": { - "key": "properties.capacityModeChangeTransitionState", - "type": "CapacityModeChangeTransitionState", - }, - "enable_materialized_views": {"key": "properties.enableMaterializedViews", "type": "bool"}, - "keys_metadata": {"key": "properties.keysMetadata", "type": "DatabaseAccountKeysMetadata"}, - "enable_partition_merge": {"key": "properties.enablePartitionMerge", "type": "bool"}, - "enable_burst_capacity": {"key": "properties.enableBurstCapacity", "type": "bool"}, - "minimal_tls_version": {"key": "properties.minimalTlsVersion", "type": "str"}, - "customer_managed_key_status": {"key": "properties.customerManagedKeyStatus", "type": "str"}, - "enable_priority_based_execution": {"key": "properties.enablePriorityBasedExecution", "type": "bool"}, - "default_priority_level": {"key": "properties.defaultPriorityLevel", "type": "str"}, - "enable_per_region_per_partition_autoscale": { - "key": "properties.enablePerRegionPerPartitionAutoscale", - "type": "bool", - }, - } - - def __init__( # pylint: disable=too-many-locals - self, - *, - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - kind: Optional[Union[str, "_models.DatabaseAccountKind"]] = None, - ip_rules: Optional[List["_models.IpAddressOrRange"]] = None, - is_virtual_network_filter_enabled: Optional[bool] = None, - enable_automatic_failover: Optional[bool] = None, - consistency_policy: Optional["_models.ConsistencyPolicy"] = None, - capabilities: Optional[List["_models.Capability"]] = None, - virtual_network_rules: Optional[List["_models.VirtualNetworkRule"]] = None, - enable_multiple_write_locations: Optional[bool] = None, - enable_cassandra_connector: Optional[bool] = None, - connector_offer: Optional[Union[str, "_models.ConnectorOffer"]] = None, - disable_key_based_metadata_write_access: Optional[bool] = None, - key_vault_key_uri: Optional[str] = None, - default_identity: Optional[str] = None, - public_network_access: Optional[Union[str, "_models.PublicNetworkAccess"]] = None, - enable_free_tier: Optional[bool] = None, - api_properties: Optional["_models.ApiProperties"] = None, - enable_analytical_storage: Optional[bool] = None, - analytical_storage_configuration: Optional["_models.AnalyticalStorageConfiguration"] = None, - create_mode: Union[str, "_models.CreateMode"] = "Default", - restore_parameters: Optional["_models.RestoreParameters"] = None, - backup_policy: Optional["_models.BackupPolicy"] = None, - cors: Optional[List["_models.CorsPolicy"]] = None, - network_acl_bypass: Optional[Union[str, "_models.NetworkAclBypass"]] = None, - network_acl_bypass_resource_ids: Optional[List[str]] = None, - diagnostic_log_settings: Optional["_models.DiagnosticLogSettings"] = None, - disable_local_auth: Optional[bool] = None, - capacity: Optional["_models.Capacity"] = None, - capacity_mode: Optional[Union[str, "_models.CapacityMode"]] = None, - capacity_mode_change_transition_state: Optional["_models.CapacityModeChangeTransitionState"] = None, - enable_materialized_views: Optional[bool] = None, - enable_partition_merge: Optional[bool] = None, - enable_burst_capacity: Optional[bool] = None, - minimal_tls_version: Optional[Union[str, "_models.MinimalTlsVersion"]] = None, - customer_managed_key_status: Optional[str] = None, - enable_priority_based_execution: Optional[bool] = None, - default_priority_level: Optional[Union[str, "_models.DefaultPriorityLevel"]] = None, - enable_per_region_per_partition_autoscale: Optional[bool] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword kind: Indicates the type of database account. This can only be set at database account - creation. Known values are: "GlobalDocumentDB", "MongoDB", and "Parse". - :paramtype kind: str or ~azure.mgmt.cosmosdb.models.DatabaseAccountKind - :keyword ip_rules: List of IpRules. - :paramtype ip_rules: list[~azure.mgmt.cosmosdb.models.IpAddressOrRange] - :keyword is_virtual_network_filter_enabled: Flag to indicate whether to enable/disable Virtual - Network ACL rules. - :paramtype is_virtual_network_filter_enabled: bool - :keyword enable_automatic_failover: Enables automatic failover of the write region in the rare - event that the region is unavailable due to an outage. Automatic failover will result in a new - write region for the account and is chosen based on the failover priorities configured for the - account. - :paramtype enable_automatic_failover: bool - :keyword consistency_policy: The consistency policy for the Cosmos DB database account. - :paramtype consistency_policy: ~azure.mgmt.cosmosdb.models.ConsistencyPolicy - :keyword capabilities: List of Cosmos DB capabilities for the account. - :paramtype capabilities: list[~azure.mgmt.cosmosdb.models.Capability] - :keyword virtual_network_rules: List of Virtual Network ACL rules configured for the Cosmos DB - account. - :paramtype virtual_network_rules: list[~azure.mgmt.cosmosdb.models.VirtualNetworkRule] - :keyword enable_multiple_write_locations: Enables the account to write in multiple locations. - :paramtype enable_multiple_write_locations: bool - :keyword enable_cassandra_connector: Enables the cassandra connector on the Cosmos DB C* - account. - :paramtype enable_cassandra_connector: bool - :keyword connector_offer: The cassandra connector offer type for the Cosmos DB database C* - account. "Small" - :paramtype connector_offer: str or ~azure.mgmt.cosmosdb.models.ConnectorOffer - :keyword disable_key_based_metadata_write_access: Disable write operations on metadata - resources (databases, containers, throughput) via account keys. - :paramtype disable_key_based_metadata_write_access: bool - :keyword key_vault_key_uri: The URI of the key vault. - :paramtype key_vault_key_uri: str - :keyword default_identity: The default identity for accessing key vault used in features like - customer managed keys. The default identity needs to be explicitly set by the users. It can be - "FirstPartyIdentity", "SystemAssignedIdentity" and more. - :paramtype default_identity: str - :keyword public_network_access: Whether requests from Public Network are allowed. Known values - are: "Enabled", "Disabled", and "SecuredByPerimeter". - :paramtype public_network_access: str or ~azure.mgmt.cosmosdb.models.PublicNetworkAccess - :keyword enable_free_tier: Flag to indicate whether Free Tier is enabled. - :paramtype enable_free_tier: bool - :keyword api_properties: API specific properties. - :paramtype api_properties: ~azure.mgmt.cosmosdb.models.ApiProperties - :keyword enable_analytical_storage: Flag to indicate whether to enable storage analytics. - :paramtype enable_analytical_storage: bool - :keyword analytical_storage_configuration: Analytical storage specific properties. - :paramtype analytical_storage_configuration: - ~azure.mgmt.cosmosdb.models.AnalyticalStorageConfiguration - :keyword create_mode: Enum to indicate the mode of account creation. Known values are: - "Default" and "Restore". - :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - :keyword restore_parameters: Parameters to indicate the information about the restore. - :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.RestoreParameters - :keyword backup_policy: The object representing the policy for taking backups on an account. - :paramtype backup_policy: ~azure.mgmt.cosmosdb.models.BackupPolicy - :keyword cors: The CORS policy for the Cosmos DB database account. - :paramtype cors: list[~azure.mgmt.cosmosdb.models.CorsPolicy] - :keyword network_acl_bypass: Indicates what services are allowed to bypass firewall checks. - Known values are: "None" and "AzureServices". - :paramtype network_acl_bypass: str or ~azure.mgmt.cosmosdb.models.NetworkAclBypass - :keyword network_acl_bypass_resource_ids: An array that contains the Resource Ids for Network - Acl Bypass for the Cosmos DB account. - :paramtype network_acl_bypass_resource_ids: list[str] - :keyword diagnostic_log_settings: The Object representing the different Diagnostic log settings - for the Cosmos DB Account. - :paramtype diagnostic_log_settings: ~azure.mgmt.cosmosdb.models.DiagnosticLogSettings - :keyword disable_local_auth: Opt-out of local authentication and ensure only MSI and AAD can be - used exclusively for authentication. - :paramtype disable_local_auth: bool - :keyword capacity: The object that represents all properties related to capacity enforcement on - an account. - :paramtype capacity: ~azure.mgmt.cosmosdb.models.Capacity - :keyword capacity_mode: Indicates the capacityMode of the Cosmos DB account. Known values are: - "None", "Provisioned", and "Serverless". - :paramtype capacity_mode: str or ~azure.mgmt.cosmosdb.models.CapacityMode - :keyword capacity_mode_change_transition_state: The object that represents the migration state - for the CapacityMode of the Cosmos DB account. - :paramtype capacity_mode_change_transition_state: - ~azure.mgmt.cosmosdb.models.CapacityModeChangeTransitionState - :keyword enable_materialized_views: Flag to indicate whether to enable MaterializedViews on the - Cosmos DB account. - :paramtype enable_materialized_views: bool - :keyword enable_partition_merge: Flag to indicate enabling/disabling of Partition Merge feature - on the account. - :paramtype enable_partition_merge: bool - :keyword enable_burst_capacity: Flag to indicate enabling/disabling of Burst Capacity Preview - feature on the account. - :paramtype enable_burst_capacity: bool - :keyword minimal_tls_version: Indicates the minimum allowed Tls version. The default is Tls - 1.0, except for Cassandra and Mongo API's, which only work with Tls 1.2. Known values are: - "Tls", "Tls11", and "Tls12". - :paramtype minimal_tls_version: str or ~azure.mgmt.cosmosdb.models.MinimalTlsVersion - :keyword customer_managed_key_status: Indicates the status of the Customer Managed Key feature - on the account. In case there are errors, the property provides troubleshooting guidance. - :paramtype customer_managed_key_status: str - :keyword enable_priority_based_execution: Flag to indicate enabling/disabling of Priority Based - Execution Preview feature on the account. - :paramtype enable_priority_based_execution: bool - :keyword default_priority_level: Enum to indicate default Priority Level of request for - Priority Based Execution. Known values are: "High" and "Low". - :paramtype default_priority_level: str or ~azure.mgmt.cosmosdb.models.DefaultPriorityLevel - :keyword enable_per_region_per_partition_autoscale: Flag to indicate enabling/disabling of - Per-Region Per-partition autoscale Preview feature on the account. - :paramtype enable_per_region_per_partition_autoscale: bool - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.kind = kind - self.system_data = None - self.provisioning_state = None - self.document_endpoint = None - self.database_account_offer_type = None - self.ip_rules = ip_rules - self.is_virtual_network_filter_enabled = is_virtual_network_filter_enabled - self.enable_automatic_failover = enable_automatic_failover - self.consistency_policy = consistency_policy - self.capabilities = capabilities - self.write_locations = None - self.read_locations = None - self.locations = None - self.failover_policies = None - self.virtual_network_rules = virtual_network_rules - self.private_endpoint_connections = None - self.enable_multiple_write_locations = enable_multiple_write_locations - self.enable_cassandra_connector = enable_cassandra_connector - self.connector_offer = connector_offer - self.disable_key_based_metadata_write_access = disable_key_based_metadata_write_access - self.key_vault_key_uri = key_vault_key_uri - self.default_identity = default_identity - self.public_network_access = public_network_access - self.enable_free_tier = enable_free_tier - self.api_properties = api_properties - self.enable_analytical_storage = enable_analytical_storage - self.analytical_storage_configuration = analytical_storage_configuration - self.instance_id = None - self.create_mode = create_mode - self.restore_parameters = restore_parameters - self.backup_policy = backup_policy - self.cors = cors - self.network_acl_bypass = network_acl_bypass - self.network_acl_bypass_resource_ids = network_acl_bypass_resource_ids - self.diagnostic_log_settings = diagnostic_log_settings - self.disable_local_auth = disable_local_auth - self.capacity = capacity - self.capacity_mode = capacity_mode - self.capacity_mode_change_transition_state = capacity_mode_change_transition_state - self.enable_materialized_views = enable_materialized_views - self.keys_metadata = None - self.enable_partition_merge = enable_partition_merge - self.enable_burst_capacity = enable_burst_capacity - self.minimal_tls_version = minimal_tls_version - self.customer_managed_key_status = customer_managed_key_status - self.enable_priority_based_execution = enable_priority_based_execution - self.default_priority_level = default_priority_level - self.enable_per_region_per_partition_autoscale = enable_per_region_per_partition_autoscale - - -class DatabaseAccountKeysMetadata(_serialization.Model): - """The metadata related to each access key for the given Cosmos DB database account. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar primary_master_key: The metadata related to the Primary Read-Write Key for the given - Cosmos DB database account. - :vartype primary_master_key: ~azure.mgmt.cosmosdb.models.AccountKeyMetadata - :ivar secondary_master_key: The metadata related to the Secondary Read-Write Key for the given - Cosmos DB database account. - :vartype secondary_master_key: ~azure.mgmt.cosmosdb.models.AccountKeyMetadata - :ivar primary_readonly_master_key: The metadata related to the Primary Read-Only Key for the - given Cosmos DB database account. - :vartype primary_readonly_master_key: ~azure.mgmt.cosmosdb.models.AccountKeyMetadata - :ivar secondary_readonly_master_key: The metadata related to the Secondary Read-Only Key for - the given Cosmos DB database account. - :vartype secondary_readonly_master_key: ~azure.mgmt.cosmosdb.models.AccountKeyMetadata - """ - - _validation = { - "primary_master_key": {"readonly": True}, - "secondary_master_key": {"readonly": True}, - "primary_readonly_master_key": {"readonly": True}, - "secondary_readonly_master_key": {"readonly": True}, - } - - _attribute_map = { - "primary_master_key": {"key": "primaryMasterKey", "type": "AccountKeyMetadata"}, - "secondary_master_key": {"key": "secondaryMasterKey", "type": "AccountKeyMetadata"}, - "primary_readonly_master_key": {"key": "primaryReadonlyMasterKey", "type": "AccountKeyMetadata"}, - "secondary_readonly_master_key": {"key": "secondaryReadonlyMasterKey", "type": "AccountKeyMetadata"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.primary_master_key = None - self.secondary_master_key = None - self.primary_readonly_master_key = None - self.secondary_readonly_master_key = None - - -class DatabaseAccountListConnectionStringsResult(_serialization.Model): # pylint: disable=name-too-long - """The connection strings for the given database account. - - :ivar connection_strings: An array that contains the connection strings for the Cosmos DB - account. - :vartype connection_strings: list[~azure.mgmt.cosmosdb.models.DatabaseAccountConnectionString] - """ - - _attribute_map = { - "connection_strings": {"key": "connectionStrings", "type": "[DatabaseAccountConnectionString]"}, - } - - def __init__( - self, *, connection_strings: Optional[List["_models.DatabaseAccountConnectionString"]] = None, **kwargs: Any - ) -> None: - """ - :keyword connection_strings: An array that contains the connection strings for the Cosmos DB - account. - :paramtype connection_strings: - list[~azure.mgmt.cosmosdb.models.DatabaseAccountConnectionString] - """ - super().__init__(**kwargs) - self.connection_strings = connection_strings - - -class DatabaseAccountListReadOnlyKeysResult(_serialization.Model): - """The read-only access keys for the given database account. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar primary_readonly_master_key: Base 64 encoded value of the primary read-only key. - :vartype primary_readonly_master_key: str - :ivar secondary_readonly_master_key: Base 64 encoded value of the secondary read-only key. - :vartype secondary_readonly_master_key: str - """ - - _validation = { - "primary_readonly_master_key": {"readonly": True}, - "secondary_readonly_master_key": {"readonly": True}, - } - - _attribute_map = { - "primary_readonly_master_key": {"key": "primaryReadonlyMasterKey", "type": "str"}, - "secondary_readonly_master_key": {"key": "secondaryReadonlyMasterKey", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.primary_readonly_master_key = None - self.secondary_readonly_master_key = None - - -class DatabaseAccountListKeysResult(DatabaseAccountListReadOnlyKeysResult): - """The access keys for the given database account. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar primary_readonly_master_key: Base 64 encoded value of the primary read-only key. - :vartype primary_readonly_master_key: str - :ivar secondary_readonly_master_key: Base 64 encoded value of the secondary read-only key. - :vartype secondary_readonly_master_key: str - :ivar primary_master_key: Base 64 encoded value of the primary read-write key. - :vartype primary_master_key: str - :ivar secondary_master_key: Base 64 encoded value of the secondary read-write key. - :vartype secondary_master_key: str - """ - - _validation = { - "primary_readonly_master_key": {"readonly": True}, - "secondary_readonly_master_key": {"readonly": True}, - "primary_master_key": {"readonly": True}, - "secondary_master_key": {"readonly": True}, - } - - _attribute_map = { - "primary_readonly_master_key": {"key": "primaryReadonlyMasterKey", "type": "str"}, - "secondary_readonly_master_key": {"key": "secondaryReadonlyMasterKey", "type": "str"}, - "primary_master_key": {"key": "primaryMasterKey", "type": "str"}, - "secondary_master_key": {"key": "secondaryMasterKey", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.primary_master_key = None - self.secondary_master_key = None - - -class DatabaseAccountRegenerateKeyParameters(_serialization.Model): - """Parameters to regenerate the keys within the database account. - - All required parameters must be populated in order to send to server. - - :ivar key_kind: The access key to regenerate. Required. Known values are: "primary", - "secondary", "primaryReadonly", and "secondaryReadonly". - :vartype key_kind: str or ~azure.mgmt.cosmosdb.models.KeyKind - """ - - _validation = { - "key_kind": {"required": True}, - } - - _attribute_map = { - "key_kind": {"key": "keyKind", "type": "str"}, - } - - def __init__(self, *, key_kind: Union[str, "_models.KeyKind"], **kwargs: Any) -> None: - """ - :keyword key_kind: The access key to regenerate. Required. Known values are: "primary", - "secondary", "primaryReadonly", and "secondaryReadonly". - :paramtype key_kind: str or ~azure.mgmt.cosmosdb.models.KeyKind - """ - super().__init__(**kwargs) - self.key_kind = key_kind - - -class DatabaseAccountsListResult(_serialization.Model): - """The List operation response, that contains the database accounts and their properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of database account and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[DatabaseAccountGetResults]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class DatabaseAccountUpdateParameters(_serialization.Model): # pylint: disable=too-many-instance-attributes - """Parameters for patching Azure Cosmos DB database account properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar consistency_policy: The consistency policy for the Cosmos DB account. - :vartype consistency_policy: ~azure.mgmt.cosmosdb.models.ConsistencyPolicy - :ivar locations: An array that contains the georeplication locations enabled for the Cosmos DB - account. - :vartype locations: list[~azure.mgmt.cosmosdb.models.Location] - :ivar ip_rules: List of IpRules. - :vartype ip_rules: list[~azure.mgmt.cosmosdb.models.IpAddressOrRange] - :ivar is_virtual_network_filter_enabled: Flag to indicate whether to enable/disable Virtual - Network ACL rules. - :vartype is_virtual_network_filter_enabled: bool - :ivar enable_automatic_failover: Enables automatic failover of the write region in the rare - event that the region is unavailable due to an outage. Automatic failover will result in a new - write region for the account and is chosen based on the failover priorities configured for the - account. - :vartype enable_automatic_failover: bool - :ivar capabilities: List of Cosmos DB capabilities for the account. - :vartype capabilities: list[~azure.mgmt.cosmosdb.models.Capability] - :ivar virtual_network_rules: List of Virtual Network ACL rules configured for the Cosmos DB - account. - :vartype virtual_network_rules: list[~azure.mgmt.cosmosdb.models.VirtualNetworkRule] - :ivar enable_multiple_write_locations: Enables the account to write in multiple locations. - :vartype enable_multiple_write_locations: bool - :ivar enable_cassandra_connector: Enables the cassandra connector on the Cosmos DB C* account. - :vartype enable_cassandra_connector: bool - :ivar connector_offer: The cassandra connector offer type for the Cosmos DB database C* - account. "Small" - :vartype connector_offer: str or ~azure.mgmt.cosmosdb.models.ConnectorOffer - :ivar disable_key_based_metadata_write_access: Disable write operations on metadata resources - (databases, containers, throughput) via account keys. - :vartype disable_key_based_metadata_write_access: bool - :ivar key_vault_key_uri: The URI of the key vault. - :vartype key_vault_key_uri: str - :ivar default_identity: The default identity for accessing key vault used in features like - customer managed keys. The default identity needs to be explicitly set by the users. It can be - "FirstPartyIdentity", "SystemAssignedIdentity" and more. - :vartype default_identity: str - :ivar public_network_access: Whether requests from Public Network are allowed. Known values - are: "Enabled", "Disabled", and "SecuredByPerimeter". - :vartype public_network_access: str or ~azure.mgmt.cosmosdb.models.PublicNetworkAccess - :ivar enable_free_tier: Flag to indicate whether Free Tier is enabled. - :vartype enable_free_tier: bool - :ivar api_properties: API specific properties. Currently, supported only for MongoDB API. - :vartype api_properties: ~azure.mgmt.cosmosdb.models.ApiProperties - :ivar enable_analytical_storage: Flag to indicate whether to enable storage analytics. - :vartype enable_analytical_storage: bool - :ivar analytical_storage_configuration: Analytical storage specific properties. - :vartype analytical_storage_configuration: - ~azure.mgmt.cosmosdb.models.AnalyticalStorageConfiguration - :ivar backup_policy: The object representing the policy for taking backups on an account. - :vartype backup_policy: ~azure.mgmt.cosmosdb.models.BackupPolicy - :ivar cors: The CORS policy for the Cosmos DB database account. - :vartype cors: list[~azure.mgmt.cosmosdb.models.CorsPolicy] - :ivar network_acl_bypass: Indicates what services are allowed to bypass firewall checks. Known - values are: "None" and "AzureServices". - :vartype network_acl_bypass: str or ~azure.mgmt.cosmosdb.models.NetworkAclBypass - :ivar network_acl_bypass_resource_ids: An array that contains the Resource Ids for Network Acl - Bypass for the Cosmos DB account. - :vartype network_acl_bypass_resource_ids: list[str] - :ivar diagnostic_log_settings: The Object representing the different Diagnostic log settings - for the Cosmos DB Account. - :vartype diagnostic_log_settings: ~azure.mgmt.cosmosdb.models.DiagnosticLogSettings - :ivar disable_local_auth: Opt-out of local authentication and ensure only MSI and AAD can be - used exclusively for authentication. - :vartype disable_local_auth: bool - :ivar capacity: The object that represents all properties related to capacity enforcement on an - account. - :vartype capacity: ~azure.mgmt.cosmosdb.models.Capacity - :ivar capacity_mode: Indicates the capacityMode of the Cosmos DB account. Known values are: - "None", "Provisioned", and "Serverless". - :vartype capacity_mode: str or ~azure.mgmt.cosmosdb.models.CapacityMode - :ivar enable_materialized_views: Flag to indicate whether to enable MaterializedViews on the - Cosmos DB account. - :vartype enable_materialized_views: bool - :ivar keys_metadata: This property is ignored during the update operation, as the metadata is - read-only. The object represents the metadata for the Account Keys of the Cosmos DB account. - :vartype keys_metadata: ~azure.mgmt.cosmosdb.models.DatabaseAccountKeysMetadata - :ivar enable_partition_merge: Flag to indicate enabling/disabling of Partition Merge feature on - the account. - :vartype enable_partition_merge: bool - :ivar enable_burst_capacity: Flag to indicate enabling/disabling of Burst Capacity Preview - feature on the account. - :vartype enable_burst_capacity: bool - :ivar minimal_tls_version: Indicates the minimum allowed Tls version. The default is Tls 1.0, - except for Cassandra and Mongo API's, which only work with Tls 1.2. Known values are: "Tls", - "Tls11", and "Tls12". - :vartype minimal_tls_version: str or ~azure.mgmt.cosmosdb.models.MinimalTlsVersion - :ivar customer_managed_key_status: Indicates the status of the Customer Managed Key feature on - the account. In case there are errors, the property provides troubleshooting guidance. - :vartype customer_managed_key_status: str - :ivar enable_priority_based_execution: Flag to indicate enabling/disabling of Priority Based - Execution Preview feature on the account. - :vartype enable_priority_based_execution: bool - :ivar default_priority_level: Enum to indicate default Priority Level of request for Priority - Based Execution. Known values are: "High" and "Low". - :vartype default_priority_level: str or ~azure.mgmt.cosmosdb.models.DefaultPriorityLevel - :ivar enable_per_region_per_partition_autoscale: Flag to indicate enabling/disabling of - Per-Region Per-partition autoscale Preview feature on the account. - :vartype enable_per_region_per_partition_autoscale: bool - """ - - _validation = { - "keys_metadata": {"readonly": True}, - } - - _attribute_map = { - "tags": {"key": "tags", "type": "{str}"}, - "location": {"key": "location", "type": "str"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "consistency_policy": {"key": "properties.consistencyPolicy", "type": "ConsistencyPolicy"}, - "locations": {"key": "properties.locations", "type": "[Location]"}, - "ip_rules": {"key": "properties.ipRules", "type": "[IpAddressOrRange]"}, - "is_virtual_network_filter_enabled": {"key": "properties.isVirtualNetworkFilterEnabled", "type": "bool"}, - "enable_automatic_failover": {"key": "properties.enableAutomaticFailover", "type": "bool"}, - "capabilities": {"key": "properties.capabilities", "type": "[Capability]"}, - "virtual_network_rules": {"key": "properties.virtualNetworkRules", "type": "[VirtualNetworkRule]"}, - "enable_multiple_write_locations": {"key": "properties.enableMultipleWriteLocations", "type": "bool"}, - "enable_cassandra_connector": {"key": "properties.enableCassandraConnector", "type": "bool"}, - "connector_offer": {"key": "properties.connectorOffer", "type": "str"}, - "disable_key_based_metadata_write_access": { - "key": "properties.disableKeyBasedMetadataWriteAccess", - "type": "bool", - }, - "key_vault_key_uri": {"key": "properties.keyVaultKeyUri", "type": "str"}, - "default_identity": {"key": "properties.defaultIdentity", "type": "str"}, - "public_network_access": {"key": "properties.publicNetworkAccess", "type": "str"}, - "enable_free_tier": {"key": "properties.enableFreeTier", "type": "bool"}, - "api_properties": {"key": "properties.apiProperties", "type": "ApiProperties"}, - "enable_analytical_storage": {"key": "properties.enableAnalyticalStorage", "type": "bool"}, - "analytical_storage_configuration": { - "key": "properties.analyticalStorageConfiguration", - "type": "AnalyticalStorageConfiguration", - }, - "backup_policy": {"key": "properties.backupPolicy", "type": "BackupPolicy"}, - "cors": {"key": "properties.cors", "type": "[CorsPolicy]"}, - "network_acl_bypass": {"key": "properties.networkAclBypass", "type": "str"}, - "network_acl_bypass_resource_ids": {"key": "properties.networkAclBypassResourceIds", "type": "[str]"}, - "diagnostic_log_settings": {"key": "properties.diagnosticLogSettings", "type": "DiagnosticLogSettings"}, - "disable_local_auth": {"key": "properties.disableLocalAuth", "type": "bool"}, - "capacity": {"key": "properties.capacity", "type": "Capacity"}, - "capacity_mode": {"key": "properties.capacityMode", "type": "str"}, - "enable_materialized_views": {"key": "properties.enableMaterializedViews", "type": "bool"}, - "keys_metadata": {"key": "properties.keysMetadata", "type": "DatabaseAccountKeysMetadata"}, - "enable_partition_merge": {"key": "properties.enablePartitionMerge", "type": "bool"}, - "enable_burst_capacity": {"key": "properties.enableBurstCapacity", "type": "bool"}, - "minimal_tls_version": {"key": "properties.minimalTlsVersion", "type": "str"}, - "customer_managed_key_status": {"key": "properties.customerManagedKeyStatus", "type": "str"}, - "enable_priority_based_execution": {"key": "properties.enablePriorityBasedExecution", "type": "bool"}, - "default_priority_level": {"key": "properties.defaultPriorityLevel", "type": "str"}, - "enable_per_region_per_partition_autoscale": { - "key": "properties.enablePerRegionPerPartitionAutoscale", - "type": "bool", - }, - } - - def __init__( # pylint: disable=too-many-locals - self, - *, - tags: Optional[Dict[str, str]] = None, - location: Optional[str] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - consistency_policy: Optional["_models.ConsistencyPolicy"] = None, - locations: Optional[List["_models.Location"]] = None, - ip_rules: Optional[List["_models.IpAddressOrRange"]] = None, - is_virtual_network_filter_enabled: Optional[bool] = None, - enable_automatic_failover: Optional[bool] = None, - capabilities: Optional[List["_models.Capability"]] = None, - virtual_network_rules: Optional[List["_models.VirtualNetworkRule"]] = None, - enable_multiple_write_locations: Optional[bool] = None, - enable_cassandra_connector: Optional[bool] = None, - connector_offer: Optional[Union[str, "_models.ConnectorOffer"]] = None, - disable_key_based_metadata_write_access: Optional[bool] = None, - key_vault_key_uri: Optional[str] = None, - default_identity: Optional[str] = None, - public_network_access: Optional[Union[str, "_models.PublicNetworkAccess"]] = None, - enable_free_tier: Optional[bool] = None, - api_properties: Optional["_models.ApiProperties"] = None, - enable_analytical_storage: Optional[bool] = None, - analytical_storage_configuration: Optional["_models.AnalyticalStorageConfiguration"] = None, - backup_policy: Optional["_models.BackupPolicy"] = None, - cors: Optional[List["_models.CorsPolicy"]] = None, - network_acl_bypass: Optional[Union[str, "_models.NetworkAclBypass"]] = None, - network_acl_bypass_resource_ids: Optional[List[str]] = None, - diagnostic_log_settings: Optional["_models.DiagnosticLogSettings"] = None, - disable_local_auth: Optional[bool] = None, - capacity: Optional["_models.Capacity"] = None, - capacity_mode: Optional[Union[str, "_models.CapacityMode"]] = None, - enable_materialized_views: Optional[bool] = None, - enable_partition_merge: Optional[bool] = None, - enable_burst_capacity: Optional[bool] = None, - minimal_tls_version: Optional[Union[str, "_models.MinimalTlsVersion"]] = None, - customer_managed_key_status: Optional[str] = None, - enable_priority_based_execution: Optional[bool] = None, - default_priority_level: Optional[Union[str, "_models.DefaultPriorityLevel"]] = None, - enable_per_region_per_partition_autoscale: Optional[bool] = None, - **kwargs: Any - ) -> None: - """ - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword consistency_policy: The consistency policy for the Cosmos DB account. - :paramtype consistency_policy: ~azure.mgmt.cosmosdb.models.ConsistencyPolicy - :keyword locations: An array that contains the georeplication locations enabled for the Cosmos - DB account. - :paramtype locations: list[~azure.mgmt.cosmosdb.models.Location] - :keyword ip_rules: List of IpRules. - :paramtype ip_rules: list[~azure.mgmt.cosmosdb.models.IpAddressOrRange] - :keyword is_virtual_network_filter_enabled: Flag to indicate whether to enable/disable Virtual - Network ACL rules. - :paramtype is_virtual_network_filter_enabled: bool - :keyword enable_automatic_failover: Enables automatic failover of the write region in the rare - event that the region is unavailable due to an outage. Automatic failover will result in a new - write region for the account and is chosen based on the failover priorities configured for the - account. - :paramtype enable_automatic_failover: bool - :keyword capabilities: List of Cosmos DB capabilities for the account. - :paramtype capabilities: list[~azure.mgmt.cosmosdb.models.Capability] - :keyword virtual_network_rules: List of Virtual Network ACL rules configured for the Cosmos DB - account. - :paramtype virtual_network_rules: list[~azure.mgmt.cosmosdb.models.VirtualNetworkRule] - :keyword enable_multiple_write_locations: Enables the account to write in multiple locations. - :paramtype enable_multiple_write_locations: bool - :keyword enable_cassandra_connector: Enables the cassandra connector on the Cosmos DB C* - account. - :paramtype enable_cassandra_connector: bool - :keyword connector_offer: The cassandra connector offer type for the Cosmos DB database C* - account. "Small" - :paramtype connector_offer: str or ~azure.mgmt.cosmosdb.models.ConnectorOffer - :keyword disable_key_based_metadata_write_access: Disable write operations on metadata - resources (databases, containers, throughput) via account keys. - :paramtype disable_key_based_metadata_write_access: bool - :keyword key_vault_key_uri: The URI of the key vault. - :paramtype key_vault_key_uri: str - :keyword default_identity: The default identity for accessing key vault used in features like - customer managed keys. The default identity needs to be explicitly set by the users. It can be - "FirstPartyIdentity", "SystemAssignedIdentity" and more. - :paramtype default_identity: str - :keyword public_network_access: Whether requests from Public Network are allowed. Known values - are: "Enabled", "Disabled", and "SecuredByPerimeter". - :paramtype public_network_access: str or ~azure.mgmt.cosmosdb.models.PublicNetworkAccess - :keyword enable_free_tier: Flag to indicate whether Free Tier is enabled. - :paramtype enable_free_tier: bool - :keyword api_properties: API specific properties. Currently, supported only for MongoDB API. - :paramtype api_properties: ~azure.mgmt.cosmosdb.models.ApiProperties - :keyword enable_analytical_storage: Flag to indicate whether to enable storage analytics. - :paramtype enable_analytical_storage: bool - :keyword analytical_storage_configuration: Analytical storage specific properties. - :paramtype analytical_storage_configuration: - ~azure.mgmt.cosmosdb.models.AnalyticalStorageConfiguration - :keyword backup_policy: The object representing the policy for taking backups on an account. - :paramtype backup_policy: ~azure.mgmt.cosmosdb.models.BackupPolicy - :keyword cors: The CORS policy for the Cosmos DB database account. - :paramtype cors: list[~azure.mgmt.cosmosdb.models.CorsPolicy] - :keyword network_acl_bypass: Indicates what services are allowed to bypass firewall checks. - Known values are: "None" and "AzureServices". - :paramtype network_acl_bypass: str or ~azure.mgmt.cosmosdb.models.NetworkAclBypass - :keyword network_acl_bypass_resource_ids: An array that contains the Resource Ids for Network - Acl Bypass for the Cosmos DB account. - :paramtype network_acl_bypass_resource_ids: list[str] - :keyword diagnostic_log_settings: The Object representing the different Diagnostic log settings - for the Cosmos DB Account. - :paramtype diagnostic_log_settings: ~azure.mgmt.cosmosdb.models.DiagnosticLogSettings - :keyword disable_local_auth: Opt-out of local authentication and ensure only MSI and AAD can be - used exclusively for authentication. - :paramtype disable_local_auth: bool - :keyword capacity: The object that represents all properties related to capacity enforcement on - an account. - :paramtype capacity: ~azure.mgmt.cosmosdb.models.Capacity - :keyword capacity_mode: Indicates the capacityMode of the Cosmos DB account. Known values are: - "None", "Provisioned", and "Serverless". - :paramtype capacity_mode: str or ~azure.mgmt.cosmosdb.models.CapacityMode - :keyword enable_materialized_views: Flag to indicate whether to enable MaterializedViews on the - Cosmos DB account. - :paramtype enable_materialized_views: bool - :keyword enable_partition_merge: Flag to indicate enabling/disabling of Partition Merge feature - on the account. - :paramtype enable_partition_merge: bool - :keyword enable_burst_capacity: Flag to indicate enabling/disabling of Burst Capacity Preview - feature on the account. - :paramtype enable_burst_capacity: bool - :keyword minimal_tls_version: Indicates the minimum allowed Tls version. The default is Tls - 1.0, except for Cassandra and Mongo API's, which only work with Tls 1.2. Known values are: - "Tls", "Tls11", and "Tls12". - :paramtype minimal_tls_version: str or ~azure.mgmt.cosmosdb.models.MinimalTlsVersion - :keyword customer_managed_key_status: Indicates the status of the Customer Managed Key feature - on the account. In case there are errors, the property provides troubleshooting guidance. - :paramtype customer_managed_key_status: str - :keyword enable_priority_based_execution: Flag to indicate enabling/disabling of Priority Based - Execution Preview feature on the account. - :paramtype enable_priority_based_execution: bool - :keyword default_priority_level: Enum to indicate default Priority Level of request for - Priority Based Execution. Known values are: "High" and "Low". - :paramtype default_priority_level: str or ~azure.mgmt.cosmosdb.models.DefaultPriorityLevel - :keyword enable_per_region_per_partition_autoscale: Flag to indicate enabling/disabling of - Per-Region Per-partition autoscale Preview feature on the account. - :paramtype enable_per_region_per_partition_autoscale: bool - """ - super().__init__(**kwargs) - self.tags = tags - self.location = location - self.identity = identity - self.consistency_policy = consistency_policy - self.locations = locations - self.ip_rules = ip_rules - self.is_virtual_network_filter_enabled = is_virtual_network_filter_enabled - self.enable_automatic_failover = enable_automatic_failover - self.capabilities = capabilities - self.virtual_network_rules = virtual_network_rules - self.enable_multiple_write_locations = enable_multiple_write_locations - self.enable_cassandra_connector = enable_cassandra_connector - self.connector_offer = connector_offer - self.disable_key_based_metadata_write_access = disable_key_based_metadata_write_access - self.key_vault_key_uri = key_vault_key_uri - self.default_identity = default_identity - self.public_network_access = public_network_access - self.enable_free_tier = enable_free_tier - self.api_properties = api_properties - self.enable_analytical_storage = enable_analytical_storage - self.analytical_storage_configuration = analytical_storage_configuration - self.backup_policy = backup_policy - self.cors = cors - self.network_acl_bypass = network_acl_bypass - self.network_acl_bypass_resource_ids = network_acl_bypass_resource_ids - self.diagnostic_log_settings = diagnostic_log_settings - self.disable_local_auth = disable_local_auth - self.capacity = capacity - self.capacity_mode = capacity_mode - self.enable_materialized_views = enable_materialized_views - self.keys_metadata = None - self.enable_partition_merge = enable_partition_merge - self.enable_burst_capacity = enable_burst_capacity - self.minimal_tls_version = minimal_tls_version - self.customer_managed_key_status = customer_managed_key_status - self.enable_priority_based_execution = enable_priority_based_execution - self.default_priority_level = default_priority_level - self.enable_per_region_per_partition_autoscale = enable_per_region_per_partition_autoscale - - -class DatabaseRestoreResource(_serialization.Model): - """Specific Databases to restore. - - :ivar database_name: The name of the database available for restore. - :vartype database_name: str - :ivar collection_names: The names of the collections available for restore. - :vartype collection_names: list[str] - """ - - _attribute_map = { - "database_name": {"key": "databaseName", "type": "str"}, - "collection_names": {"key": "collectionNames", "type": "[str]"}, - } - - def __init__( - self, *, database_name: Optional[str] = None, collection_names: Optional[List[str]] = None, **kwargs: Any - ) -> None: - """ - :keyword database_name: The name of the database available for restore. - :paramtype database_name: str - :keyword collection_names: The names of the collections available for restore. - :paramtype collection_names: list[str] - """ - super().__init__(**kwargs) - self.database_name = database_name - self.collection_names = collection_names - - -class DataCenterResource(ARMProxyResource): - """A managed Cassandra data center. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the database account. - :vartype id: str - :ivar name: The name of the database account. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar properties: Properties of a managed Cassandra data center. - :vartype properties: ~azure.mgmt.cosmosdb.models.DataCenterResourceProperties - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "properties": {"key": "properties", "type": "DataCenterResourceProperties"}, - } - - def __init__(self, *, properties: Optional["_models.DataCenterResourceProperties"] = None, **kwargs: Any) -> None: - """ - :keyword properties: Properties of a managed Cassandra data center. - :paramtype properties: ~azure.mgmt.cosmosdb.models.DataCenterResourceProperties - """ - super().__init__(**kwargs) - self.properties = properties - - -class DataCenterResourceProperties(_serialization.Model): # pylint: disable=too-many-instance-attributes - """Properties of a managed Cassandra data center. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar provisioning_state: The status of the resource at the time the operation was called. - Known values are: "Creating", "Updating", "Deleting", "Succeeded", "Failed", and "Canceled". - :vartype provisioning_state: str or - ~azure.mgmt.cosmosdb.models.ManagedCassandraProvisioningState - :ivar data_center_location: The region this data center should be created in. - :vartype data_center_location: str - :ivar delegated_subnet_id: Resource id of a subnet the nodes in this data center should have - their network interfaces connected to. The subnet must be in the same region specified in - 'dataCenterLocation' and must be able to route to the subnet specified in the cluster's - 'delegatedManagementSubnetId' property. This resource id will be of the form - '/subscriptions/:code:``/resourceGroups/:code:``/providers/Microsoft.Network/virtualNetworks/:code:``/subnets/:code:``'. - :vartype delegated_subnet_id: str - :ivar node_count: The number of nodes the data center should have. This is the desired number. - After it is set, it may take some time for the data center to be scaled to match. To monitor - the number of nodes and their status, use the fetchNodeStatus method on the cluster. - :vartype node_count: int - :ivar seed_nodes: IP addresses for seed nodes in this data center. This is for reference. - Generally you will want to use the seedNodes property on the cluster, which aggregates the seed - nodes from all data centers in the cluster. - :vartype seed_nodes: list[~azure.mgmt.cosmosdb.models.SeedNode] - :ivar base64_encoded_cassandra_yaml_fragment: A fragment of a cassandra.yaml configuration file - to be included in the cassandra.yaml for all nodes in this data center. The fragment should be - Base64 encoded, and only a subset of keys are allowed. - :vartype base64_encoded_cassandra_yaml_fragment: str - :ivar managed_disk_customer_key_uri: Key uri to use for encryption of managed disks. Ensure the - system assigned identity of the cluster has been assigned appropriate permissions(key - get/wrap/unwrap permissions) on the key. - :vartype managed_disk_customer_key_uri: str - :ivar backup_storage_customer_key_uri: Indicates the Key Uri of the customer key to use for - encryption of the backup storage account. - :vartype backup_storage_customer_key_uri: str - :ivar sku: Virtual Machine SKU used for data centers. Default value is Standard_DS14_v2. - :vartype sku: str - :ivar disk_sku: Disk SKU used for data centers. Default value is P30. - :vartype disk_sku: str - :ivar disk_capacity: Number of disks attached to each node. Default is 4. - :vartype disk_capacity: int - :ivar availability_zone: If the data center has Availability Zone support, apply it to the - Virtual Machine ScaleSet that host the cassandra data center virtual machines. - :vartype availability_zone: bool - :ivar authentication_method_ldap_properties: Ldap authentication method properties. This - feature is in preview. - :vartype authentication_method_ldap_properties: - ~azure.mgmt.cosmosdb.models.AuthenticationMethodLdapProperties - :ivar deallocated: Whether the data center has been deallocated. - :vartype deallocated: bool - :ivar provision_error: Error related to resource provisioning. - :vartype provision_error: ~azure.mgmt.cosmosdb.models.CassandraError - :ivar private_endpoint_ip_address: Ip of the VPN Endpoint for this data center. - :vartype private_endpoint_ip_address: str - """ - - _validation = { - "seed_nodes": {"readonly": True}, - } - - _attribute_map = { - "provisioning_state": {"key": "provisioningState", "type": "str"}, - "data_center_location": {"key": "dataCenterLocation", "type": "str"}, - "delegated_subnet_id": {"key": "delegatedSubnetId", "type": "str"}, - "node_count": {"key": "nodeCount", "type": "int"}, - "seed_nodes": {"key": "seedNodes", "type": "[SeedNode]"}, - "base64_encoded_cassandra_yaml_fragment": {"key": "base64EncodedCassandraYamlFragment", "type": "str"}, - "managed_disk_customer_key_uri": {"key": "managedDiskCustomerKeyUri", "type": "str"}, - "backup_storage_customer_key_uri": {"key": "backupStorageCustomerKeyUri", "type": "str"}, - "sku": {"key": "sku", "type": "str"}, - "disk_sku": {"key": "diskSku", "type": "str"}, - "disk_capacity": {"key": "diskCapacity", "type": "int"}, - "availability_zone": {"key": "availabilityZone", "type": "bool"}, - "authentication_method_ldap_properties": { - "key": "authenticationMethodLdapProperties", - "type": "AuthenticationMethodLdapProperties", - }, - "deallocated": {"key": "deallocated", "type": "bool"}, - "provision_error": {"key": "provisionError", "type": "CassandraError"}, - "private_endpoint_ip_address": {"key": "privateEndpointIpAddress", "type": "str"}, - } - - def __init__( - self, - *, - provisioning_state: Optional[Union[str, "_models.ManagedCassandraProvisioningState"]] = None, - data_center_location: Optional[str] = None, - delegated_subnet_id: Optional[str] = None, - node_count: Optional[int] = None, - base64_encoded_cassandra_yaml_fragment: Optional[str] = None, - managed_disk_customer_key_uri: Optional[str] = None, - backup_storage_customer_key_uri: Optional[str] = None, - sku: Optional[str] = None, - disk_sku: Optional[str] = None, - disk_capacity: Optional[int] = None, - availability_zone: Optional[bool] = None, - authentication_method_ldap_properties: Optional["_models.AuthenticationMethodLdapProperties"] = None, - deallocated: Optional[bool] = None, - provision_error: Optional["_models.CassandraError"] = None, - private_endpoint_ip_address: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword provisioning_state: The status of the resource at the time the operation was called. - Known values are: "Creating", "Updating", "Deleting", "Succeeded", "Failed", and "Canceled". - :paramtype provisioning_state: str or - ~azure.mgmt.cosmosdb.models.ManagedCassandraProvisioningState - :keyword data_center_location: The region this data center should be created in. - :paramtype data_center_location: str - :keyword delegated_subnet_id: Resource id of a subnet the nodes in this data center should have - their network interfaces connected to. The subnet must be in the same region specified in - 'dataCenterLocation' and must be able to route to the subnet specified in the cluster's - 'delegatedManagementSubnetId' property. This resource id will be of the form - '/subscriptions/:code:``/resourceGroups/:code:``/providers/Microsoft.Network/virtualNetworks/:code:``/subnets/:code:``'. - :paramtype delegated_subnet_id: str - :keyword node_count: The number of nodes the data center should have. This is the desired - number. After it is set, it may take some time for the data center to be scaled to match. To - monitor the number of nodes and their status, use the fetchNodeStatus method on the cluster. - :paramtype node_count: int - :keyword base64_encoded_cassandra_yaml_fragment: A fragment of a cassandra.yaml configuration - file to be included in the cassandra.yaml for all nodes in this data center. The fragment - should be Base64 encoded, and only a subset of keys are allowed. - :paramtype base64_encoded_cassandra_yaml_fragment: str - :keyword managed_disk_customer_key_uri: Key uri to use for encryption of managed disks. Ensure - the system assigned identity of the cluster has been assigned appropriate permissions(key - get/wrap/unwrap permissions) on the key. - :paramtype managed_disk_customer_key_uri: str - :keyword backup_storage_customer_key_uri: Indicates the Key Uri of the customer key to use for - encryption of the backup storage account. - :paramtype backup_storage_customer_key_uri: str - :keyword sku: Virtual Machine SKU used for data centers. Default value is Standard_DS14_v2. - :paramtype sku: str - :keyword disk_sku: Disk SKU used for data centers. Default value is P30. - :paramtype disk_sku: str - :keyword disk_capacity: Number of disks attached to each node. Default is 4. - :paramtype disk_capacity: int - :keyword availability_zone: If the data center has Availability Zone support, apply it to the - Virtual Machine ScaleSet that host the cassandra data center virtual machines. - :paramtype availability_zone: bool - :keyword authentication_method_ldap_properties: Ldap authentication method properties. This - feature is in preview. - :paramtype authentication_method_ldap_properties: - ~azure.mgmt.cosmosdb.models.AuthenticationMethodLdapProperties - :keyword deallocated: Whether the data center has been deallocated. - :paramtype deallocated: bool - :keyword provision_error: Error related to resource provisioning. - :paramtype provision_error: ~azure.mgmt.cosmosdb.models.CassandraError - :keyword private_endpoint_ip_address: Ip of the VPN Endpoint for this data center. - :paramtype private_endpoint_ip_address: str - """ - super().__init__(**kwargs) - self.provisioning_state = provisioning_state - self.data_center_location = data_center_location - self.delegated_subnet_id = delegated_subnet_id - self.node_count = node_count - self.seed_nodes = None - self.base64_encoded_cassandra_yaml_fragment = base64_encoded_cassandra_yaml_fragment - self.managed_disk_customer_key_uri = managed_disk_customer_key_uri - self.backup_storage_customer_key_uri = backup_storage_customer_key_uri - self.sku = sku - self.disk_sku = disk_sku - self.disk_capacity = disk_capacity - self.availability_zone = availability_zone - self.authentication_method_ldap_properties = authentication_method_ldap_properties - self.deallocated = deallocated - self.provision_error = provision_error - self.private_endpoint_ip_address = private_endpoint_ip_address - - -class DataTransferJobFeedResults(_serialization.Model): - """The List operation response, that contains the Data Transfer jobs and their properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of Data Transfer jobs and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.DataTransferJobGetResults] - :ivar next_link: URL to get the next set of Data Transfer job list results if there are any. - :vartype next_link: str - """ - - _validation = { - "value": {"readonly": True}, - "next_link": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[DataTransferJobGetResults]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - self.next_link = None - - -class DataTransferJobGetResults(ARMProxyResource): # pylint: disable=too-many-instance-attributes - """A Cosmos DB Data Transfer Job. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the database account. - :vartype id: str - :ivar name: The name of the database account. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar job_name: Job Name. - :vartype job_name: str - :ivar source: Source DataStore details. - :vartype source: ~azure.mgmt.cosmosdb.models.DataTransferDataSourceSink - :ivar destination: Destination DataStore details. - :vartype destination: ~azure.mgmt.cosmosdb.models.DataTransferDataSourceSink - :ivar status: Job Status. - :vartype status: str - :ivar processed_count: Processed Count. - :vartype processed_count: int - :ivar total_count: Total Count. - :vartype total_count: int - :ivar last_updated_utc_time: Last Updated Time (ISO-8601 format). - :vartype last_updated_utc_time: ~datetime.datetime - :ivar worker_count: Worker count. - :vartype worker_count: int - :ivar error: Error response for Faulted job. - :vartype error: ~azure.mgmt.cosmosdb.models.ErrorResponse - :ivar duration: Total Duration of Job. - :vartype duration: str - :ivar mode: Mode of job execution. Known values are: "Offline" and "Online". - :vartype mode: str or ~azure.mgmt.cosmosdb.models.DataTransferJobMode - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "job_name": {"readonly": True}, - "status": {"readonly": True}, - "processed_count": {"readonly": True}, - "total_count": {"readonly": True}, - "last_updated_utc_time": {"readonly": True}, - "worker_count": {"minimum": 0}, - "error": {"readonly": True}, - "duration": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "job_name": {"key": "properties.jobName", "type": "str"}, - "source": {"key": "properties.source", "type": "DataTransferDataSourceSink"}, - "destination": {"key": "properties.destination", "type": "DataTransferDataSourceSink"}, - "status": {"key": "properties.status", "type": "str"}, - "processed_count": {"key": "properties.processedCount", "type": "int"}, - "total_count": {"key": "properties.totalCount", "type": "int"}, - "last_updated_utc_time": {"key": "properties.lastUpdatedUtcTime", "type": "iso-8601"}, - "worker_count": {"key": "properties.workerCount", "type": "int"}, - "error": {"key": "properties.error", "type": "ErrorResponse"}, - "duration": {"key": "properties.duration", "type": "str"}, - "mode": {"key": "properties.mode", "type": "str"}, - } - - def __init__( - self, - *, - source: Optional["_models.DataTransferDataSourceSink"] = None, - destination: Optional["_models.DataTransferDataSourceSink"] = None, - worker_count: Optional[int] = None, - mode: Optional[Union[str, "_models.DataTransferJobMode"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword source: Source DataStore details. - :paramtype source: ~azure.mgmt.cosmosdb.models.DataTransferDataSourceSink - :keyword destination: Destination DataStore details. - :paramtype destination: ~azure.mgmt.cosmosdb.models.DataTransferDataSourceSink - :keyword worker_count: Worker count. - :paramtype worker_count: int - :keyword mode: Mode of job execution. Known values are: "Offline" and "Online". - :paramtype mode: str or ~azure.mgmt.cosmosdb.models.DataTransferJobMode - """ - super().__init__(**kwargs) - self.job_name = None - self.source = source - self.destination = destination - self.status = None - self.processed_count = None - self.total_count = None - self.last_updated_utc_time = None - self.worker_count = worker_count - self.error = None - self.duration = None - self.mode = mode - - -class DataTransferJobProperties(_serialization.Model): # pylint: disable=too-many-instance-attributes - """The properties of a DataTransfer Job. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar job_name: Job Name. - :vartype job_name: str - :ivar source: Source DataStore details. Required. - :vartype source: ~azure.mgmt.cosmosdb.models.DataTransferDataSourceSink - :ivar destination: Destination DataStore details. Required. - :vartype destination: ~azure.mgmt.cosmosdb.models.DataTransferDataSourceSink - :ivar status: Job Status. - :vartype status: str - :ivar processed_count: Processed Count. - :vartype processed_count: int - :ivar total_count: Total Count. - :vartype total_count: int - :ivar last_updated_utc_time: Last Updated Time (ISO-8601 format). - :vartype last_updated_utc_time: ~datetime.datetime - :ivar worker_count: Worker count. - :vartype worker_count: int - :ivar error: Error response for Faulted job. - :vartype error: ~azure.mgmt.cosmosdb.models.ErrorResponse - :ivar duration: Total Duration of Job. - :vartype duration: str - :ivar mode: Mode of job execution. Known values are: "Offline" and "Online". - :vartype mode: str or ~azure.mgmt.cosmosdb.models.DataTransferJobMode - """ - - _validation = { - "job_name": {"readonly": True}, - "source": {"required": True}, - "destination": {"required": True}, - "status": {"readonly": True}, - "processed_count": {"readonly": True}, - "total_count": {"readonly": True}, - "last_updated_utc_time": {"readonly": True}, - "worker_count": {"minimum": 0}, - "error": {"readonly": True}, - "duration": {"readonly": True}, - } - - _attribute_map = { - "job_name": {"key": "jobName", "type": "str"}, - "source": {"key": "source", "type": "DataTransferDataSourceSink"}, - "destination": {"key": "destination", "type": "DataTransferDataSourceSink"}, - "status": {"key": "status", "type": "str"}, - "processed_count": {"key": "processedCount", "type": "int"}, - "total_count": {"key": "totalCount", "type": "int"}, - "last_updated_utc_time": {"key": "lastUpdatedUtcTime", "type": "iso-8601"}, - "worker_count": {"key": "workerCount", "type": "int"}, - "error": {"key": "error", "type": "ErrorResponse"}, - "duration": {"key": "duration", "type": "str"}, - "mode": {"key": "mode", "type": "str"}, - } - - def __init__( - self, - *, - source: "_models.DataTransferDataSourceSink", - destination: "_models.DataTransferDataSourceSink", - worker_count: Optional[int] = None, - mode: Optional[Union[str, "_models.DataTransferJobMode"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword source: Source DataStore details. Required. - :paramtype source: ~azure.mgmt.cosmosdb.models.DataTransferDataSourceSink - :keyword destination: Destination DataStore details. Required. - :paramtype destination: ~azure.mgmt.cosmosdb.models.DataTransferDataSourceSink - :keyword worker_count: Worker count. - :paramtype worker_count: int - :keyword mode: Mode of job execution. Known values are: "Offline" and "Online". - :paramtype mode: str or ~azure.mgmt.cosmosdb.models.DataTransferJobMode - """ - super().__init__(**kwargs) - self.job_name = None - self.source = source - self.destination = destination - self.status = None - self.processed_count = None - self.total_count = None - self.last_updated_utc_time = None - self.worker_count = worker_count - self.error = None - self.duration = None - self.mode = mode - - -class RegionalServiceResource(_serialization.Model): - """Resource for a regional service location. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar name: The regional service name. - :vartype name: str - :ivar location: The location name. - :vartype location: str - :ivar status: Describes the status of a service. Known values are: "Creating", "Running", - "Updating", "Deleting", "Error", and "Stopped". - :vartype status: str or ~azure.mgmt.cosmosdb.models.ServiceStatus - """ - - _validation = { - "name": {"readonly": True}, - "location": {"readonly": True}, - "status": {"readonly": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "status": {"key": "status", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.name = None - self.location = None - self.status = None - - -class DataTransferRegionalServiceResource(RegionalServiceResource): - """Resource for a regional service location. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar name: The regional service name. - :vartype name: str - :ivar location: The location name. - :vartype location: str - :ivar status: Describes the status of a service. Known values are: "Creating", "Running", - "Updating", "Deleting", "Error", and "Stopped". - :vartype status: str or ~azure.mgmt.cosmosdb.models.ServiceStatus - """ - - -class DataTransferServiceResource(_serialization.Model): - """Describes the service response property. - - :ivar properties: Properties for DataTransferServiceResource. - :vartype properties: ~azure.mgmt.cosmosdb.models.DataTransferServiceResourceProperties - """ - - _attribute_map = { - "properties": {"key": "properties", "type": "DataTransferServiceResourceProperties"}, - } - - def __init__( - self, *, properties: Optional["_models.DataTransferServiceResourceProperties"] = None, **kwargs: Any - ) -> None: - """ - :keyword properties: Properties for DataTransferServiceResource. - :paramtype properties: ~azure.mgmt.cosmosdb.models.DataTransferServiceResourceProperties - """ - super().__init__(**kwargs) - self.properties = properties - - -class ServiceResourceCreateUpdateProperties(_serialization.Model): - """Properties in ServiceResourceCreateUpdateParameters. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - DataTransferServiceResourceCreateUpdateProperties, - GraphAPIComputeServiceResourceCreateUpdateProperties, - MaterializedViewsBuilderServiceResourceCreateUpdateProperties, - SqlDedicatedGatewayServiceResourceCreateUpdateProperties - - All required parameters must be populated in order to send to server. - - :ivar instance_size: Instance type for the service. Known values are: "Cosmos.D4s", - "Cosmos.D8s", and "Cosmos.D16s". - :vartype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize - :ivar instance_count: Instance count for the service. - :vartype instance_count: int - :ivar service_type: ServiceType for the service. Required. Known values are: - "SqlDedicatedGateway", "DataTransfer", "GraphAPICompute", and "MaterializedViewsBuilder". - :vartype service_type: str or ~azure.mgmt.cosmosdb.models.ServiceType - """ - - _validation = { - "instance_count": {"minimum": 0}, - "service_type": {"required": True}, - } - - _attribute_map = { - "instance_size": {"key": "instanceSize", "type": "str"}, - "instance_count": {"key": "instanceCount", "type": "int"}, - "service_type": {"key": "serviceType", "type": "str"}, - } - - _subtype_map = { - "service_type": { - "DataTransfer": "DataTransferServiceResourceCreateUpdateProperties", - "GraphAPICompute": "GraphAPIComputeServiceResourceCreateUpdateProperties", - "MaterializedViewsBuilder": "MaterializedViewsBuilderServiceResourceCreateUpdateProperties", - "SqlDedicatedGateway": "SqlDedicatedGatewayServiceResourceCreateUpdateProperties", - } - } - - def __init__( - self, - *, - instance_size: Optional[Union[str, "_models.ServiceSize"]] = None, - instance_count: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword instance_size: Instance type for the service. Known values are: "Cosmos.D4s", - "Cosmos.D8s", and "Cosmos.D16s". - :paramtype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize - :keyword instance_count: Instance count for the service. - :paramtype instance_count: int - """ - super().__init__(**kwargs) - self.instance_size = instance_size - self.instance_count = instance_count - self.service_type: Optional[str] = None - - -class DataTransferServiceResourceCreateUpdateProperties( - ServiceResourceCreateUpdateProperties -): # pylint: disable=name-too-long - """Properties for Create or Update request for DataTransferServiceResource. - - All required parameters must be populated in order to send to server. - - :ivar instance_size: Instance type for the service. Known values are: "Cosmos.D4s", - "Cosmos.D8s", and "Cosmos.D16s". - :vartype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize - :ivar instance_count: Instance count for the service. - :vartype instance_count: int - :ivar service_type: ServiceType for the service. Required. Known values are: - "SqlDedicatedGateway", "DataTransfer", "GraphAPICompute", and "MaterializedViewsBuilder". - :vartype service_type: str or ~azure.mgmt.cosmosdb.models.ServiceType - """ - - _validation = { - "instance_count": {"minimum": 0}, - "service_type": {"required": True}, - } - - _attribute_map = { - "instance_size": {"key": "instanceSize", "type": "str"}, - "instance_count": {"key": "instanceCount", "type": "int"}, - "service_type": {"key": "serviceType", "type": "str"}, - } - - def __init__( - self, - *, - instance_size: Optional[Union[str, "_models.ServiceSize"]] = None, - instance_count: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword instance_size: Instance type for the service. Known values are: "Cosmos.D4s", - "Cosmos.D8s", and "Cosmos.D16s". - :paramtype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize - :keyword instance_count: Instance count for the service. - :paramtype instance_count: int - """ - super().__init__(instance_size=instance_size, instance_count=instance_count, **kwargs) - self.service_type: str = "DataTransfer" - - -class ServiceResourceProperties(_serialization.Model): - """Services response resource. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - DataTransferServiceResourceProperties, GraphAPIComputeServiceResourceProperties, - MaterializedViewsBuilderServiceResourceProperties, SqlDedicatedGatewayServiceResourceProperties - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar additional_properties: Unmatched properties from the message are deserialized to this - collection. - :vartype additional_properties: dict[str, any] - :ivar creation_time: Time of the last state change (ISO-8601 format). - :vartype creation_time: ~datetime.datetime - :ivar instance_size: Instance type for the service. Known values are: "Cosmos.D4s", - "Cosmos.D8s", and "Cosmos.D16s". - :vartype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize - :ivar instance_count: Instance count for the service. - :vartype instance_count: int - :ivar service_type: ServiceType for the service. Required. Known values are: - "SqlDedicatedGateway", "DataTransfer", "GraphAPICompute", and "MaterializedViewsBuilder". - :vartype service_type: str or ~azure.mgmt.cosmosdb.models.ServiceType - :ivar status: Describes the status of a service. Known values are: "Creating", "Running", - "Updating", "Deleting", "Error", and "Stopped". - :vartype status: str or ~azure.mgmt.cosmosdb.models.ServiceStatus - """ - - _validation = { - "creation_time": {"readonly": True}, - "instance_count": {"minimum": 0}, - "service_type": {"required": True}, - "status": {"readonly": True}, - } - - _attribute_map = { - "additional_properties": {"key": "", "type": "{object}"}, - "creation_time": {"key": "creationTime", "type": "iso-8601"}, - "instance_size": {"key": "instanceSize", "type": "str"}, - "instance_count": {"key": "instanceCount", "type": "int"}, - "service_type": {"key": "serviceType", "type": "str"}, - "status": {"key": "status", "type": "str"}, - } - - _subtype_map = { - "service_type": { - "DataTransfer": "DataTransferServiceResourceProperties", - "GraphAPICompute": "GraphAPIComputeServiceResourceProperties", - "MaterializedViewsBuilder": "MaterializedViewsBuilderServiceResourceProperties", - "SqlDedicatedGateway": "SqlDedicatedGatewayServiceResourceProperties", - } - } - - def __init__( - self, - *, - additional_properties: Optional[Dict[str, Any]] = None, - instance_size: Optional[Union[str, "_models.ServiceSize"]] = None, - instance_count: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword additional_properties: Unmatched properties from the message are deserialized to this - collection. - :paramtype additional_properties: dict[str, any] - :keyword instance_size: Instance type for the service. Known values are: "Cosmos.D4s", - "Cosmos.D8s", and "Cosmos.D16s". - :paramtype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize - :keyword instance_count: Instance count for the service. - :paramtype instance_count: int - """ - super().__init__(**kwargs) - self.additional_properties = additional_properties - self.creation_time = None - self.instance_size = instance_size - self.instance_count = instance_count - self.service_type: Optional[str] = None - self.status = None - - -class DataTransferServiceResourceProperties(ServiceResourceProperties): - """Properties for DataTransferServiceResource. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar additional_properties: Unmatched properties from the message are deserialized to this - collection. - :vartype additional_properties: dict[str, any] - :ivar creation_time: Time of the last state change (ISO-8601 format). - :vartype creation_time: ~datetime.datetime - :ivar instance_size: Instance type for the service. Known values are: "Cosmos.D4s", - "Cosmos.D8s", and "Cosmos.D16s". - :vartype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize - :ivar instance_count: Instance count for the service. - :vartype instance_count: int - :ivar service_type: ServiceType for the service. Required. Known values are: - "SqlDedicatedGateway", "DataTransfer", "GraphAPICompute", and "MaterializedViewsBuilder". - :vartype service_type: str or ~azure.mgmt.cosmosdb.models.ServiceType - :ivar status: Describes the status of a service. Known values are: "Creating", "Running", - "Updating", "Deleting", "Error", and "Stopped". - :vartype status: str or ~azure.mgmt.cosmosdb.models.ServiceStatus - :ivar locations: An array that contains all of the locations for the service. - :vartype locations: list[~azure.mgmt.cosmosdb.models.DataTransferRegionalServiceResource] - """ - - _validation = { - "creation_time": {"readonly": True}, - "instance_count": {"minimum": 0}, - "service_type": {"required": True}, - "status": {"readonly": True}, - "locations": {"readonly": True}, - } - - _attribute_map = { - "additional_properties": {"key": "", "type": "{object}"}, - "creation_time": {"key": "creationTime", "type": "iso-8601"}, - "instance_size": {"key": "instanceSize", "type": "str"}, - "instance_count": {"key": "instanceCount", "type": "int"}, - "service_type": {"key": "serviceType", "type": "str"}, - "status": {"key": "status", "type": "str"}, - "locations": {"key": "locations", "type": "[DataTransferRegionalServiceResource]"}, - } - - def __init__( - self, - *, - additional_properties: Optional[Dict[str, Any]] = None, - instance_size: Optional[Union[str, "_models.ServiceSize"]] = None, - instance_count: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword additional_properties: Unmatched properties from the message are deserialized to this - collection. - :paramtype additional_properties: dict[str, any] - :keyword instance_size: Instance type for the service. Known values are: "Cosmos.D4s", - "Cosmos.D8s", and "Cosmos.D16s". - :paramtype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize - :keyword instance_count: Instance count for the service. - :paramtype instance_count: int - """ - super().__init__( - additional_properties=additional_properties, - instance_size=instance_size, - instance_count=instance_count, - **kwargs - ) - self.service_type: str = "DataTransfer" - self.locations = None - - -class DiagnosticLogSettings(_serialization.Model): - """Indicates what diagnostic log settings are to be enabled. - - :ivar enable_full_text_query: Describe the level of detail with which queries are to be logged. - Known values are: "None", "True", and "False". - :vartype enable_full_text_query: str or ~azure.mgmt.cosmosdb.models.EnableFullTextQuery - """ - - _attribute_map = { - "enable_full_text_query": {"key": "enableFullTextQuery", "type": "str"}, - } - - def __init__( - self, *, enable_full_text_query: Optional[Union[str, "_models.EnableFullTextQuery"]] = None, **kwargs: Any - ) -> None: - """ - :keyword enable_full_text_query: Describe the level of detail with which queries are to be - logged. Known values are: "None", "True", and "False". - :paramtype enable_full_text_query: str or ~azure.mgmt.cosmosdb.models.EnableFullTextQuery - """ - super().__init__(**kwargs) - self.enable_full_text_query = enable_full_text_query - - -class ErrorAdditionalInfo(_serialization.Model): - """The resource management error additional info. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: JSON - """ - - _validation = { - "type": {"readonly": True}, - "info": {"readonly": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "info": {"key": "info", "type": "object"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.type = None - self.info = None - - -class ErrorDetail(_serialization.Model): - """The error detail. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.mgmt.cosmosdb.models.ErrorDetail] - :ivar additional_info: The error additional info. - :vartype additional_info: list[~azure.mgmt.cosmosdb.models.ErrorAdditionalInfo] - """ - - _validation = { - "code": {"readonly": True}, - "message": {"readonly": True}, - "target": {"readonly": True}, - "details": {"readonly": True}, - "additional_info": {"readonly": True}, - } - - _attribute_map = { - "code": {"key": "code", "type": "str"}, - "message": {"key": "message", "type": "str"}, - "target": {"key": "target", "type": "str"}, - "details": {"key": "details", "type": "[ErrorDetail]"}, - "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.code = None - self.message = None - self.target = None - self.details = None - self.additional_info = None - - -class ErrorResponse(_serialization.Model): - """Error Response. - - :ivar code: Error code. - :vartype code: str - :ivar message: Error message indicating why the operation failed. - :vartype message: str - """ - - _attribute_map = { - "code": {"key": "code", "type": "str"}, - "message": {"key": "message", "type": "str"}, - } - - def __init__(self, *, code: Optional[str] = None, message: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword code: Error code. - :paramtype code: str - :keyword message: Error message indicating why the operation failed. - :paramtype message: str - """ - super().__init__(**kwargs) - self.code = code - self.message = message - - -class ErrorResponseAutoGenerated(_serialization.Model): - """Common error response for all Azure Resource Manager APIs to return error details for failed - operations. (This also follows the OData error response format.). - - :ivar error: The error object. - :vartype error: ~azure.mgmt.cosmosdb.models.ErrorDetail - """ - - _attribute_map = { - "error": {"key": "error", "type": "ErrorDetail"}, - } - - def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs: Any) -> None: - """ - :keyword error: The error object. - :paramtype error: ~azure.mgmt.cosmosdb.models.ErrorDetail - """ - super().__init__(**kwargs) - self.error = error - - -class ExcludedPath(_serialization.Model): - """ExcludedPath. - - :ivar path: The path for which the indexing behavior applies to. Index paths typically start - with root and end with wildcard (/path/*). - :vartype path: str - """ - - _attribute_map = { - "path": {"key": "path", "type": "str"}, - } - - def __init__(self, *, path: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword path: The path for which the indexing behavior applies to. Index paths typically start - with root and end with wildcard (/path/*). - :paramtype path: str - """ - super().__init__(**kwargs) - self.path = path - - -class FailoverPolicies(_serialization.Model): - """The list of new failover policies for the failover priority change. - - All required parameters must be populated in order to send to server. - - :ivar failover_policies: List of failover policies. Required. - :vartype failover_policies: list[~azure.mgmt.cosmosdb.models.FailoverPolicy] - """ - - _validation = { - "failover_policies": {"required": True}, - } - - _attribute_map = { - "failover_policies": {"key": "failoverPolicies", "type": "[FailoverPolicy]"}, - } - - def __init__(self, *, failover_policies: List["_models.FailoverPolicy"], **kwargs: Any) -> None: - """ - :keyword failover_policies: List of failover policies. Required. - :paramtype failover_policies: list[~azure.mgmt.cosmosdb.models.FailoverPolicy] - """ - super().__init__(**kwargs) - self.failover_policies = failover_policies - - -class FailoverPolicy(_serialization.Model): - """The failover policy for a given region of a database account. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique identifier of the region in which the database account replicates to. - Example: <accountName>-<locationName>. - :vartype id: str - :ivar location_name: The name of the region in which the database account exists. - :vartype location_name: str - :ivar failover_priority: The failover priority of the region. A failover priority of 0 - indicates a write region. The maximum value for a failover priority = (total number of regions - - 1). Failover priority values must be unique for each of the regions in which the database - account exists. - :vartype failover_priority: int - """ - - _validation = { - "id": {"readonly": True}, - "failover_priority": {"minimum": 0}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "location_name": {"key": "locationName", "type": "str"}, - "failover_priority": {"key": "failoverPriority", "type": "int"}, - } - - def __init__( - self, *, location_name: Optional[str] = None, failover_priority: Optional[int] = None, **kwargs: Any - ) -> None: - """ - :keyword location_name: The name of the region in which the database account exists. - :paramtype location_name: str - :keyword failover_priority: The failover priority of the region. A failover priority of 0 - indicates a write region. The maximum value for a failover priority = (total number of regions - - 1). Failover priority values must be unique for each of the regions in which the database - account exists. - :paramtype failover_priority: int - """ - super().__init__(**kwargs) - self.id = None - self.location_name = location_name - self.failover_priority = failover_priority - - -class GraphAPIComputeRegionalServiceResource(RegionalServiceResource): - """Resource for a regional service location. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar name: The regional service name. - :vartype name: str - :ivar location: The location name. - :vartype location: str - :ivar status: Describes the status of a service. Known values are: "Creating", "Running", - "Updating", "Deleting", "Error", and "Stopped". - :vartype status: str or ~azure.mgmt.cosmosdb.models.ServiceStatus - :ivar graph_api_compute_endpoint: The regional endpoint for GraphAPICompute. - :vartype graph_api_compute_endpoint: str - """ - - _validation = { - "name": {"readonly": True}, - "location": {"readonly": True}, - "status": {"readonly": True}, - "graph_api_compute_endpoint": {"readonly": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "status": {"key": "status", "type": "str"}, - "graph_api_compute_endpoint": {"key": "graphApiComputeEndpoint", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.graph_api_compute_endpoint = None - - -class GraphAPIComputeServiceResource(_serialization.Model): - """Describes the service response property for GraphAPICompute. - - :ivar properties: Properties for GraphAPIComputeServiceResource. - :vartype properties: ~azure.mgmt.cosmosdb.models.GraphAPIComputeServiceResourceProperties - """ - - _attribute_map = { - "properties": {"key": "properties", "type": "GraphAPIComputeServiceResourceProperties"}, - } - - def __init__( - self, *, properties: Optional["_models.GraphAPIComputeServiceResourceProperties"] = None, **kwargs: Any - ) -> None: - """ - :keyword properties: Properties for GraphAPIComputeServiceResource. - :paramtype properties: ~azure.mgmt.cosmosdb.models.GraphAPIComputeServiceResourceProperties - """ - super().__init__(**kwargs) - self.properties = properties - - -class GraphAPIComputeServiceResourceCreateUpdateProperties( - ServiceResourceCreateUpdateProperties -): # pylint: disable=name-too-long - """Properties for Create or Update request for GraphAPIComputeServiceResource. - - All required parameters must be populated in order to send to server. - - :ivar instance_size: Instance type for the service. Known values are: "Cosmos.D4s", - "Cosmos.D8s", and "Cosmos.D16s". - :vartype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize - :ivar instance_count: Instance count for the service. - :vartype instance_count: int - :ivar service_type: ServiceType for the service. Required. Known values are: - "SqlDedicatedGateway", "DataTransfer", "GraphAPICompute", and "MaterializedViewsBuilder". - :vartype service_type: str or ~azure.mgmt.cosmosdb.models.ServiceType - """ - - _validation = { - "instance_count": {"minimum": 0}, - "service_type": {"required": True}, - } - - _attribute_map = { - "instance_size": {"key": "instanceSize", "type": "str"}, - "instance_count": {"key": "instanceCount", "type": "int"}, - "service_type": {"key": "serviceType", "type": "str"}, - } - - def __init__( - self, - *, - instance_size: Optional[Union[str, "_models.ServiceSize"]] = None, - instance_count: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword instance_size: Instance type for the service. Known values are: "Cosmos.D4s", - "Cosmos.D8s", and "Cosmos.D16s". - :paramtype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize - :keyword instance_count: Instance count for the service. - :paramtype instance_count: int - """ - super().__init__(instance_size=instance_size, instance_count=instance_count, **kwargs) - self.service_type: str = "GraphAPICompute" - - -class GraphAPIComputeServiceResourceProperties(ServiceResourceProperties): - """Properties for GraphAPIComputeServiceResource. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar additional_properties: Unmatched properties from the message are deserialized to this - collection. - :vartype additional_properties: dict[str, any] - :ivar creation_time: Time of the last state change (ISO-8601 format). - :vartype creation_time: ~datetime.datetime - :ivar instance_size: Instance type for the service. Known values are: "Cosmos.D4s", - "Cosmos.D8s", and "Cosmos.D16s". - :vartype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize - :ivar instance_count: Instance count for the service. - :vartype instance_count: int - :ivar service_type: ServiceType for the service. Required. Known values are: - "SqlDedicatedGateway", "DataTransfer", "GraphAPICompute", and "MaterializedViewsBuilder". - :vartype service_type: str or ~azure.mgmt.cosmosdb.models.ServiceType - :ivar status: Describes the status of a service. Known values are: "Creating", "Running", - "Updating", "Deleting", "Error", and "Stopped". - :vartype status: str or ~azure.mgmt.cosmosdb.models.ServiceStatus - :ivar graph_api_compute_endpoint: GraphAPICompute endpoint for the service. - :vartype graph_api_compute_endpoint: str - :ivar locations: An array that contains all of the locations for the service. - :vartype locations: list[~azure.mgmt.cosmosdb.models.GraphAPIComputeRegionalServiceResource] - """ - - _validation = { - "creation_time": {"readonly": True}, - "instance_count": {"minimum": 0}, - "service_type": {"required": True}, - "status": {"readonly": True}, - "locations": {"readonly": True}, - } - - _attribute_map = { - "additional_properties": {"key": "", "type": "{object}"}, - "creation_time": {"key": "creationTime", "type": "iso-8601"}, - "instance_size": {"key": "instanceSize", "type": "str"}, - "instance_count": {"key": "instanceCount", "type": "int"}, - "service_type": {"key": "serviceType", "type": "str"}, - "status": {"key": "status", "type": "str"}, - "graph_api_compute_endpoint": {"key": "graphApiComputeEndpoint", "type": "str"}, - "locations": {"key": "locations", "type": "[GraphAPIComputeRegionalServiceResource]"}, - } - - def __init__( - self, - *, - additional_properties: Optional[Dict[str, Any]] = None, - instance_size: Optional[Union[str, "_models.ServiceSize"]] = None, - instance_count: Optional[int] = None, - graph_api_compute_endpoint: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword additional_properties: Unmatched properties from the message are deserialized to this - collection. - :paramtype additional_properties: dict[str, any] - :keyword instance_size: Instance type for the service. Known values are: "Cosmos.D4s", - "Cosmos.D8s", and "Cosmos.D16s". - :paramtype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize - :keyword instance_count: Instance count for the service. - :paramtype instance_count: int - :keyword graph_api_compute_endpoint: GraphAPICompute endpoint for the service. - :paramtype graph_api_compute_endpoint: str - """ - super().__init__( - additional_properties=additional_properties, - instance_size=instance_size, - instance_count=instance_count, - **kwargs - ) - self.service_type: str = "GraphAPICompute" - self.graph_api_compute_endpoint = graph_api_compute_endpoint - self.locations = None - - -class GraphResource(_serialization.Model): - """Cosmos DB Graph resource object. - - All required parameters must be populated in order to send to server. - - :ivar id: Name of the Cosmos DB Graph. Required. - :vartype id: str - """ - - _validation = { - "id": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - } - - def __init__(self, *, id: str, **kwargs: Any) -> None: # pylint: disable=redefined-builtin - """ - :keyword id: Name of the Cosmos DB Graph. Required. - :paramtype id: str - """ - super().__init__(**kwargs) - self.id = id - - -class GraphResourceCreateUpdateParameters(ARMResourceProperties): - """Parameters to create and update Cosmos DB Graph resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: The standard JSON format of a Graph resource. Required. - :vartype resource: ~azure.mgmt.cosmosdb.models.GraphResource - :ivar options: A key-value pair of options to be applied for the request. This corresponds to - the headers sent with the request. - :vartype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "resource": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "GraphResource"}, - "options": {"key": "properties.options", "type": "CreateUpdateOptions"}, - } - - def __init__( - self, - *, - resource: "_models.GraphResource", - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - options: Optional["_models.CreateUpdateOptions"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: The standard JSON format of a Graph resource. Required. - :paramtype resource: ~azure.mgmt.cosmosdb.models.GraphResource - :keyword options: A key-value pair of options to be applied for the request. This corresponds - to the headers sent with the request. - :paramtype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - self.options = options - - -class GraphResourceGetPropertiesOptions(OptionsResource): - """GraphResourceGetPropertiesOptions. - - :ivar throughput: Value of the Cosmos DB resource throughput or autoscaleSettings. Use the - ThroughputSetting resource when retrieving offer details. - :vartype throughput: int - :ivar autoscale_settings: Specifies the Autoscale settings. - :vartype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettings - """ - - -class GraphResourceGetPropertiesResource(GraphResource): - """GraphResourceGetPropertiesResource. - - All required parameters must be populated in order to send to server. - - :ivar id: Name of the Cosmos DB Graph. Required. - :vartype id: str - """ - - -class GraphResourceGetResults(ARMResourceProperties): - """An Azure Cosmos DB Graph resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: - :vartype resource: ~azure.mgmt.cosmosdb.models.GraphResourceGetPropertiesResource - :ivar options: - :vartype options: ~azure.mgmt.cosmosdb.models.GraphResourceGetPropertiesOptions - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "GraphResourceGetPropertiesResource"}, - "options": {"key": "properties.options", "type": "GraphResourceGetPropertiesOptions"}, - } - - def __init__( - self, - *, - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - resource: Optional["_models.GraphResourceGetPropertiesResource"] = None, - options: Optional["_models.GraphResourceGetPropertiesOptions"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: - :paramtype resource: ~azure.mgmt.cosmosdb.models.GraphResourceGetPropertiesResource - :keyword options: - :paramtype options: ~azure.mgmt.cosmosdb.models.GraphResourceGetPropertiesOptions - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - self.options = options - - -class GraphResourcesListResult(_serialization.Model): - """The List operation response, that contains the Graph resource and their properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of Graph resource and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.GraphResourceGetResults] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[GraphResourceGetResults]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class GremlinDatabaseCreateUpdateParameters(ARMResourceProperties): - """Parameters to create and update Cosmos DB Gremlin database. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: The standard JSON format of a Gremlin database. Required. - :vartype resource: ~azure.mgmt.cosmosdb.models.GremlinDatabaseResource - :ivar options: A key-value pair of options to be applied for the request. This corresponds to - the headers sent with the request. - :vartype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "resource": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "GremlinDatabaseResource"}, - "options": {"key": "properties.options", "type": "CreateUpdateOptions"}, - } - - def __init__( - self, - *, - resource: "_models.GremlinDatabaseResource", - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - options: Optional["_models.CreateUpdateOptions"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: The standard JSON format of a Gremlin database. Required. - :paramtype resource: ~azure.mgmt.cosmosdb.models.GremlinDatabaseResource - :keyword options: A key-value pair of options to be applied for the request. This corresponds - to the headers sent with the request. - :paramtype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - self.options = options - - -class GremlinDatabaseGetPropertiesOptions(OptionsResource): - """GremlinDatabaseGetPropertiesOptions. - - :ivar throughput: Value of the Cosmos DB resource throughput or autoscaleSettings. Use the - ThroughputSetting resource when retrieving offer details. - :vartype throughput: int - :ivar autoscale_settings: Specifies the Autoscale settings. - :vartype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettings - """ - - -class GremlinDatabaseResource(_serialization.Model): - """Cosmos DB Gremlin database resource object. - - All required parameters must be populated in order to send to server. - - :ivar id: Name of the Cosmos DB Gremlin database. Required. - :vartype id: str - :ivar restore_parameters: Parameters to indicate the information about the restore. - :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" - and "Restore". - :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - """ - - _validation = { - "id": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, - "create_mode": {"key": "createMode", "type": "str"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, - create_mode: Union[str, "_models.CreateMode"] = "Default", - **kwargs: Any - ) -> None: - """ - :keyword id: Name of the Cosmos DB Gremlin database. Required. - :paramtype id: str - :keyword restore_parameters: Parameters to indicate the information about the restore. - :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: - "Default" and "Restore". - :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - """ - super().__init__(**kwargs) - self.id = id - self.restore_parameters = restore_parameters - self.create_mode = create_mode - - -class GremlinDatabaseGetPropertiesResource(GremlinDatabaseResource, ExtendedResourceProperties): - """GremlinDatabaseGetPropertiesResource. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar rid: A system generated property. A unique identifier. - :vartype rid: str - :ivar ts: A system generated property that denotes the last updated timestamp of the resource. - :vartype ts: float - :ivar etag: A system generated property representing the resource etag required for optimistic - concurrency control. - :vartype etag: str - :ivar id: Name of the Cosmos DB Gremlin database. Required. - :vartype id: str - :ivar restore_parameters: Parameters to indicate the information about the restore. - :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" - and "Restore". - :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - """ - - _validation = { - "rid": {"readonly": True}, - "ts": {"readonly": True}, - "etag": {"readonly": True}, - "id": {"required": True}, - } - - _attribute_map = { - "rid": {"key": "_rid", "type": "str"}, - "ts": {"key": "_ts", "type": "float"}, - "etag": {"key": "_etag", "type": "str"}, - "id": {"key": "id", "type": "str"}, - "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, - "create_mode": {"key": "createMode", "type": "str"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, - create_mode: Union[str, "_models.CreateMode"] = "Default", - **kwargs: Any - ) -> None: - """ - :keyword id: Name of the Cosmos DB Gremlin database. Required. - :paramtype id: str - :keyword restore_parameters: Parameters to indicate the information about the restore. - :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: - "Default" and "Restore". - :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - """ - super().__init__(id=id, restore_parameters=restore_parameters, create_mode=create_mode, **kwargs) - self.rid = None - self.ts = None - self.etag = None - self.id = id - self.restore_parameters = restore_parameters - self.create_mode = create_mode - - -class GremlinDatabaseGetResults(ARMResourceProperties): - """An Azure Cosmos DB Gremlin database. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: - :vartype resource: ~azure.mgmt.cosmosdb.models.GremlinDatabaseGetPropertiesResource - :ivar options: - :vartype options: ~azure.mgmt.cosmosdb.models.GremlinDatabaseGetPropertiesOptions - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "GremlinDatabaseGetPropertiesResource"}, - "options": {"key": "properties.options", "type": "GremlinDatabaseGetPropertiesOptions"}, - } - - def __init__( - self, - *, - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - resource: Optional["_models.GremlinDatabaseGetPropertiesResource"] = None, - options: Optional["_models.GremlinDatabaseGetPropertiesOptions"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: - :paramtype resource: ~azure.mgmt.cosmosdb.models.GremlinDatabaseGetPropertiesResource - :keyword options: - :paramtype options: ~azure.mgmt.cosmosdb.models.GremlinDatabaseGetPropertiesOptions - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - self.options = options - - -class GremlinDatabaseListResult(_serialization.Model): - """The List operation response, that contains the Gremlin databases and their properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of Gremlin databases and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[GremlinDatabaseGetResults]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class GremlinDatabaseRestoreResource(_serialization.Model): - """Specific Gremlin Databases to restore. - - :ivar database_name: The name of the gremlin database available for restore. - :vartype database_name: str - :ivar graph_names: The names of the graphs available for restore. - :vartype graph_names: list[str] - """ - - _attribute_map = { - "database_name": {"key": "databaseName", "type": "str"}, - "graph_names": {"key": "graphNames", "type": "[str]"}, - } - - def __init__( - self, *, database_name: Optional[str] = None, graph_names: Optional[List[str]] = None, **kwargs: Any - ) -> None: - """ - :keyword database_name: The name of the gremlin database available for restore. - :paramtype database_name: str - :keyword graph_names: The names of the graphs available for restore. - :paramtype graph_names: list[str] - """ - super().__init__(**kwargs) - self.database_name = database_name - self.graph_names = graph_names - - -class GremlinGraphCreateUpdateParameters(ARMResourceProperties): - """Parameters to create and update Cosmos DB Gremlin graph. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: The standard JSON format of a Gremlin graph. Required. - :vartype resource: ~azure.mgmt.cosmosdb.models.GremlinGraphResource - :ivar options: A key-value pair of options to be applied for the request. This corresponds to - the headers sent with the request. - :vartype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "resource": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "GremlinGraphResource"}, - "options": {"key": "properties.options", "type": "CreateUpdateOptions"}, - } - - def __init__( - self, - *, - resource: "_models.GremlinGraphResource", - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - options: Optional["_models.CreateUpdateOptions"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: The standard JSON format of a Gremlin graph. Required. - :paramtype resource: ~azure.mgmt.cosmosdb.models.GremlinGraphResource - :keyword options: A key-value pair of options to be applied for the request. This corresponds - to the headers sent with the request. - :paramtype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - self.options = options - - -class GremlinGraphGetPropertiesOptions(OptionsResource): - """GremlinGraphGetPropertiesOptions. - - :ivar throughput: Value of the Cosmos DB resource throughput or autoscaleSettings. Use the - ThroughputSetting resource when retrieving offer details. - :vartype throughput: int - :ivar autoscale_settings: Specifies the Autoscale settings. - :vartype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettings - """ - - -class GremlinGraphResource(_serialization.Model): - """Cosmos DB Gremlin graph resource object. - - All required parameters must be populated in order to send to server. - - :ivar id: Name of the Cosmos DB Gremlin graph. Required. - :vartype id: str - :ivar indexing_policy: The configuration of the indexing policy. By default, the indexing is - automatic for all document paths within the graph. - :vartype indexing_policy: ~azure.mgmt.cosmosdb.models.IndexingPolicy - :ivar partition_key: The configuration of the partition key to be used for partitioning data - into multiple partitions. - :vartype partition_key: ~azure.mgmt.cosmosdb.models.ContainerPartitionKey - :ivar default_ttl: Default time to live. - :vartype default_ttl: int - :ivar unique_key_policy: The unique key policy configuration for specifying uniqueness - constraints on documents in the collection in the Azure Cosmos DB service. - :vartype unique_key_policy: ~azure.mgmt.cosmosdb.models.UniqueKeyPolicy - :ivar conflict_resolution_policy: The conflict resolution policy for the graph. - :vartype conflict_resolution_policy: ~azure.mgmt.cosmosdb.models.ConflictResolutionPolicy - :ivar analytical_storage_ttl: Analytical TTL. - :vartype analytical_storage_ttl: int - :ivar restore_parameters: Parameters to indicate the information about the restore. - :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" - and "Restore". - :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - """ - - _validation = { - "id": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "indexing_policy": {"key": "indexingPolicy", "type": "IndexingPolicy"}, - "partition_key": {"key": "partitionKey", "type": "ContainerPartitionKey"}, - "default_ttl": {"key": "defaultTtl", "type": "int"}, - "unique_key_policy": {"key": "uniqueKeyPolicy", "type": "UniqueKeyPolicy"}, - "conflict_resolution_policy": {"key": "conflictResolutionPolicy", "type": "ConflictResolutionPolicy"}, - "analytical_storage_ttl": {"key": "analyticalStorageTtl", "type": "int"}, - "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, - "create_mode": {"key": "createMode", "type": "str"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - indexing_policy: Optional["_models.IndexingPolicy"] = None, - partition_key: Optional["_models.ContainerPartitionKey"] = None, - default_ttl: Optional[int] = None, - unique_key_policy: Optional["_models.UniqueKeyPolicy"] = None, - conflict_resolution_policy: Optional["_models.ConflictResolutionPolicy"] = None, - analytical_storage_ttl: Optional[int] = None, - restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, - create_mode: Union[str, "_models.CreateMode"] = "Default", - **kwargs: Any - ) -> None: - """ - :keyword id: Name of the Cosmos DB Gremlin graph. Required. - :paramtype id: str - :keyword indexing_policy: The configuration of the indexing policy. By default, the indexing is - automatic for all document paths within the graph. - :paramtype indexing_policy: ~azure.mgmt.cosmosdb.models.IndexingPolicy - :keyword partition_key: The configuration of the partition key to be used for partitioning data - into multiple partitions. - :paramtype partition_key: ~azure.mgmt.cosmosdb.models.ContainerPartitionKey - :keyword default_ttl: Default time to live. - :paramtype default_ttl: int - :keyword unique_key_policy: The unique key policy configuration for specifying uniqueness - constraints on documents in the collection in the Azure Cosmos DB service. - :paramtype unique_key_policy: ~azure.mgmt.cosmosdb.models.UniqueKeyPolicy - :keyword conflict_resolution_policy: The conflict resolution policy for the graph. - :paramtype conflict_resolution_policy: ~azure.mgmt.cosmosdb.models.ConflictResolutionPolicy - :keyword analytical_storage_ttl: Analytical TTL. - :paramtype analytical_storage_ttl: int - :keyword restore_parameters: Parameters to indicate the information about the restore. - :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: - "Default" and "Restore". - :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - """ - super().__init__(**kwargs) - self.id = id - self.indexing_policy = indexing_policy - self.partition_key = partition_key - self.default_ttl = default_ttl - self.unique_key_policy = unique_key_policy - self.conflict_resolution_policy = conflict_resolution_policy - self.analytical_storage_ttl = analytical_storage_ttl - self.restore_parameters = restore_parameters - self.create_mode = create_mode - - -class GremlinGraphGetPropertiesResource( - GremlinGraphResource, ExtendedResourceProperties -): # pylint: disable=too-many-instance-attributes - """GremlinGraphGetPropertiesResource. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar rid: A system generated property. A unique identifier. - :vartype rid: str - :ivar ts: A system generated property that denotes the last updated timestamp of the resource. - :vartype ts: float - :ivar etag: A system generated property representing the resource etag required for optimistic - concurrency control. - :vartype etag: str - :ivar id: Name of the Cosmos DB Gremlin graph. Required. - :vartype id: str - :ivar indexing_policy: The configuration of the indexing policy. By default, the indexing is - automatic for all document paths within the graph. - :vartype indexing_policy: ~azure.mgmt.cosmosdb.models.IndexingPolicy - :ivar partition_key: The configuration of the partition key to be used for partitioning data - into multiple partitions. - :vartype partition_key: ~azure.mgmt.cosmosdb.models.ContainerPartitionKey - :ivar default_ttl: Default time to live. - :vartype default_ttl: int - :ivar unique_key_policy: The unique key policy configuration for specifying uniqueness - constraints on documents in the collection in the Azure Cosmos DB service. - :vartype unique_key_policy: ~azure.mgmt.cosmosdb.models.UniqueKeyPolicy - :ivar conflict_resolution_policy: The conflict resolution policy for the graph. - :vartype conflict_resolution_policy: ~azure.mgmt.cosmosdb.models.ConflictResolutionPolicy - :ivar analytical_storage_ttl: Analytical TTL. - :vartype analytical_storage_ttl: int - :ivar restore_parameters: Parameters to indicate the information about the restore. - :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" - and "Restore". - :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - """ - - _validation = { - "rid": {"readonly": True}, - "ts": {"readonly": True}, - "etag": {"readonly": True}, - "id": {"required": True}, - } - - _attribute_map = { - "rid": {"key": "_rid", "type": "str"}, - "ts": {"key": "_ts", "type": "float"}, - "etag": {"key": "_etag", "type": "str"}, - "id": {"key": "id", "type": "str"}, - "indexing_policy": {"key": "indexingPolicy", "type": "IndexingPolicy"}, - "partition_key": {"key": "partitionKey", "type": "ContainerPartitionKey"}, - "default_ttl": {"key": "defaultTtl", "type": "int"}, - "unique_key_policy": {"key": "uniqueKeyPolicy", "type": "UniqueKeyPolicy"}, - "conflict_resolution_policy": {"key": "conflictResolutionPolicy", "type": "ConflictResolutionPolicy"}, - "analytical_storage_ttl": {"key": "analyticalStorageTtl", "type": "int"}, - "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, - "create_mode": {"key": "createMode", "type": "str"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - indexing_policy: Optional["_models.IndexingPolicy"] = None, - partition_key: Optional["_models.ContainerPartitionKey"] = None, - default_ttl: Optional[int] = None, - unique_key_policy: Optional["_models.UniqueKeyPolicy"] = None, - conflict_resolution_policy: Optional["_models.ConflictResolutionPolicy"] = None, - analytical_storage_ttl: Optional[int] = None, - restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, - create_mode: Union[str, "_models.CreateMode"] = "Default", - **kwargs: Any - ) -> None: - """ - :keyword id: Name of the Cosmos DB Gremlin graph. Required. - :paramtype id: str - :keyword indexing_policy: The configuration of the indexing policy. By default, the indexing is - automatic for all document paths within the graph. - :paramtype indexing_policy: ~azure.mgmt.cosmosdb.models.IndexingPolicy - :keyword partition_key: The configuration of the partition key to be used for partitioning data - into multiple partitions. - :paramtype partition_key: ~azure.mgmt.cosmosdb.models.ContainerPartitionKey - :keyword default_ttl: Default time to live. - :paramtype default_ttl: int - :keyword unique_key_policy: The unique key policy configuration for specifying uniqueness - constraints on documents in the collection in the Azure Cosmos DB service. - :paramtype unique_key_policy: ~azure.mgmt.cosmosdb.models.UniqueKeyPolicy - :keyword conflict_resolution_policy: The conflict resolution policy for the graph. - :paramtype conflict_resolution_policy: ~azure.mgmt.cosmosdb.models.ConflictResolutionPolicy - :keyword analytical_storage_ttl: Analytical TTL. - :paramtype analytical_storage_ttl: int - :keyword restore_parameters: Parameters to indicate the information about the restore. - :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: - "Default" and "Restore". - :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - """ - super().__init__( - id=id, - indexing_policy=indexing_policy, - partition_key=partition_key, - default_ttl=default_ttl, - unique_key_policy=unique_key_policy, - conflict_resolution_policy=conflict_resolution_policy, - analytical_storage_ttl=analytical_storage_ttl, - restore_parameters=restore_parameters, - create_mode=create_mode, - **kwargs - ) - self.rid = None - self.ts = None - self.etag = None - self.id = id - self.indexing_policy = indexing_policy - self.partition_key = partition_key - self.default_ttl = default_ttl - self.unique_key_policy = unique_key_policy - self.conflict_resolution_policy = conflict_resolution_policy - self.analytical_storage_ttl = analytical_storage_ttl - self.restore_parameters = restore_parameters - self.create_mode = create_mode - - -class GremlinGraphGetResults(ARMResourceProperties): - """An Azure Cosmos DB Gremlin graph. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: - :vartype resource: ~azure.mgmt.cosmosdb.models.GremlinGraphGetPropertiesResource - :ivar options: - :vartype options: ~azure.mgmt.cosmosdb.models.GremlinGraphGetPropertiesOptions - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "GremlinGraphGetPropertiesResource"}, - "options": {"key": "properties.options", "type": "GremlinGraphGetPropertiesOptions"}, - } - - def __init__( - self, - *, - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - resource: Optional["_models.GremlinGraphGetPropertiesResource"] = None, - options: Optional["_models.GremlinGraphGetPropertiesOptions"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: - :paramtype resource: ~azure.mgmt.cosmosdb.models.GremlinGraphGetPropertiesResource - :keyword options: - :paramtype options: ~azure.mgmt.cosmosdb.models.GremlinGraphGetPropertiesOptions - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - self.options = options - - -class GremlinGraphListResult(_serialization.Model): - """The List operation response, that contains the graphs and their properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of graphs and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.GremlinGraphGetResults] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[GremlinGraphGetResults]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class IncludedPath(_serialization.Model): - """The paths that are included in indexing. - - :ivar path: The path for which the indexing behavior applies to. Index paths typically start - with root and end with wildcard (/path/*). - :vartype path: str - :ivar indexes: List of indexes for this path. - :vartype indexes: list[~azure.mgmt.cosmosdb.models.Indexes] - """ - - _attribute_map = { - "path": {"key": "path", "type": "str"}, - "indexes": {"key": "indexes", "type": "[Indexes]"}, - } - - def __init__( - self, *, path: Optional[str] = None, indexes: Optional[List["_models.Indexes"]] = None, **kwargs: Any - ) -> None: - """ - :keyword path: The path for which the indexing behavior applies to. Index paths typically start - with root and end with wildcard (/path/*). - :paramtype path: str - :keyword indexes: List of indexes for this path. - :paramtype indexes: list[~azure.mgmt.cosmosdb.models.Indexes] - """ - super().__init__(**kwargs) - self.path = path - self.indexes = indexes - - -class Indexes(_serialization.Model): - """The indexes for the path. - - :ivar data_type: The datatype for which the indexing behavior is applied to. Known values are: - "String", "Number", "Point", "Polygon", "LineString", and "MultiPolygon". - :vartype data_type: str or ~azure.mgmt.cosmosdb.models.DataType - :ivar precision: The precision of the index. -1 is maximum precision. - :vartype precision: int - :ivar kind: Indicates the type of index. Known values are: "Hash", "Range", and "Spatial". - :vartype kind: str or ~azure.mgmt.cosmosdb.models.IndexKind - """ - - _attribute_map = { - "data_type": {"key": "dataType", "type": "str"}, - "precision": {"key": "precision", "type": "int"}, - "kind": {"key": "kind", "type": "str"}, - } - - def __init__( - self, - *, - data_type: Union[str, "_models.DataType"] = "String", - precision: Optional[int] = None, - kind: Union[str, "_models.IndexKind"] = "Hash", - **kwargs: Any - ) -> None: - """ - :keyword data_type: The datatype for which the indexing behavior is applied to. Known values - are: "String", "Number", "Point", "Polygon", "LineString", and "MultiPolygon". - :paramtype data_type: str or ~azure.mgmt.cosmosdb.models.DataType - :keyword precision: The precision of the index. -1 is maximum precision. - :paramtype precision: int - :keyword kind: Indicates the type of index. Known values are: "Hash", "Range", and "Spatial". - :paramtype kind: str or ~azure.mgmt.cosmosdb.models.IndexKind - """ - super().__init__(**kwargs) - self.data_type = data_type - self.precision = precision - self.kind = kind - - -class IndexingPolicy(_serialization.Model): - """Cosmos DB indexing policy. - - :ivar automatic: Indicates if the indexing policy is automatic. - :vartype automatic: bool - :ivar indexing_mode: Indicates the indexing mode. Known values are: "consistent", "lazy", and - "none". - :vartype indexing_mode: str or ~azure.mgmt.cosmosdb.models.IndexingMode - :ivar included_paths: List of paths to include in the indexing. - :vartype included_paths: list[~azure.mgmt.cosmosdb.models.IncludedPath] - :ivar excluded_paths: List of paths to exclude from indexing. - :vartype excluded_paths: list[~azure.mgmt.cosmosdb.models.ExcludedPath] - :ivar composite_indexes: List of composite path list. - :vartype composite_indexes: list[list[~azure.mgmt.cosmosdb.models.CompositePath]] - :ivar spatial_indexes: List of spatial specifics. - :vartype spatial_indexes: list[~azure.mgmt.cosmosdb.models.SpatialSpec] - """ - - _attribute_map = { - "automatic": {"key": "automatic", "type": "bool"}, - "indexing_mode": {"key": "indexingMode", "type": "str"}, - "included_paths": {"key": "includedPaths", "type": "[IncludedPath]"}, - "excluded_paths": {"key": "excludedPaths", "type": "[ExcludedPath]"}, - "composite_indexes": {"key": "compositeIndexes", "type": "[[CompositePath]]"}, - "spatial_indexes": {"key": "spatialIndexes", "type": "[SpatialSpec]"}, - } - - def __init__( - self, - *, - automatic: Optional[bool] = None, - indexing_mode: Union[str, "_models.IndexingMode"] = "consistent", - included_paths: Optional[List["_models.IncludedPath"]] = None, - excluded_paths: Optional[List["_models.ExcludedPath"]] = None, - composite_indexes: Optional[List[List["_models.CompositePath"]]] = None, - spatial_indexes: Optional[List["_models.SpatialSpec"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword automatic: Indicates if the indexing policy is automatic. - :paramtype automatic: bool - :keyword indexing_mode: Indicates the indexing mode. Known values are: "consistent", "lazy", - and "none". - :paramtype indexing_mode: str or ~azure.mgmt.cosmosdb.models.IndexingMode - :keyword included_paths: List of paths to include in the indexing. - :paramtype included_paths: list[~azure.mgmt.cosmosdb.models.IncludedPath] - :keyword excluded_paths: List of paths to exclude from indexing. - :paramtype excluded_paths: list[~azure.mgmt.cosmosdb.models.ExcludedPath] - :keyword composite_indexes: List of composite path list. - :paramtype composite_indexes: list[list[~azure.mgmt.cosmosdb.models.CompositePath]] - :keyword spatial_indexes: List of spatial specifics. - :paramtype spatial_indexes: list[~azure.mgmt.cosmosdb.models.SpatialSpec] - """ - super().__init__(**kwargs) - self.automatic = automatic - self.indexing_mode = indexing_mode - self.included_paths = included_paths - self.excluded_paths = excluded_paths - self.composite_indexes = composite_indexes - self.spatial_indexes = spatial_indexes - - -class IpAddressOrRange(_serialization.Model): - """IpAddressOrRange object. - - :ivar ip_address_or_range: A single IPv4 address or a single IPv4 address range in CIDR format. - Provided IPs must be well-formatted and cannot be contained in one of the following ranges: - 10.0.0.0/8, 100.64.0.0/10, 172.16.0.0/12, 192.168.0.0/16, since these are not enforceable by - the IP address filter. Example of valid inputs: “23.40.210.245” or “23.40.210.0/8”. - :vartype ip_address_or_range: str - """ - - _attribute_map = { - "ip_address_or_range": {"key": "ipAddressOrRange", "type": "str"}, - } - - def __init__(self, *, ip_address_or_range: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword ip_address_or_range: A single IPv4 address or a single IPv4 address range in CIDR - format. Provided IPs must be well-formatted and cannot be contained in one of the following - ranges: 10.0.0.0/8, 100.64.0.0/10, 172.16.0.0/12, 192.168.0.0/16, since these are not - enforceable by the IP address filter. Example of valid inputs: “23.40.210.245” or - “23.40.210.0/8”. - :paramtype ip_address_or_range: str - """ - super().__init__(**kwargs) - self.ip_address_or_range = ip_address_or_range - - -class KeyWrapMetadata(_serialization.Model): - """Represents key wrap metadata that a key wrapping provider can use to wrap/unwrap a client - encryption key. - - :ivar name: The name of associated KeyEncryptionKey (aka CustomerManagedKey). - :vartype name: str - :ivar type: ProviderName of KeyStoreProvider. - :vartype type: str - :ivar value: Reference / link to the KeyEncryptionKey. - :vartype value: str - :ivar algorithm: Algorithm used in wrapping and unwrapping of the data encryption key. - :vartype algorithm: str - """ - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "value": {"key": "value", "type": "str"}, - "algorithm": {"key": "algorithm", "type": "str"}, - } - - def __init__( - self, - *, - name: Optional[str] = None, - type: Optional[str] = None, - value: Optional[str] = None, - algorithm: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The name of associated KeyEncryptionKey (aka CustomerManagedKey). - :paramtype name: str - :keyword type: ProviderName of KeyStoreProvider. - :paramtype type: str - :keyword value: Reference / link to the KeyEncryptionKey. - :paramtype value: str - :keyword algorithm: Algorithm used in wrapping and unwrapping of the data encryption key. - :paramtype algorithm: str - """ - super().__init__(**kwargs) - self.name = name - self.type = type - self.value = value - self.algorithm = algorithm - - -class ListBackups(_serialization.Model): - """List of restorable backups for a Cassandra cluster. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: Container for array of backups. - :vartype value: list[~azure.mgmt.cosmosdb.models.BackupResource] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[BackupResource]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class ListClusters(_serialization.Model): - """List of managed Cassandra clusters. - - :ivar value: Container for the array of clusters. - :vartype value: list[~azure.mgmt.cosmosdb.models.ClusterResource] - """ - - _attribute_map = { - "value": {"key": "value", "type": "[ClusterResource]"}, - } - - def __init__(self, *, value: Optional[List["_models.ClusterResource"]] = None, **kwargs: Any) -> None: - """ - :keyword value: Container for the array of clusters. - :paramtype value: list[~azure.mgmt.cosmosdb.models.ClusterResource] - """ - super().__init__(**kwargs) - self.value = value - - -class ListCommands(_serialization.Model): - """List of commands for cluster. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: Container for array of commands. - :vartype value: list[~azure.mgmt.cosmosdb.models.CommandPublicResource] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[CommandPublicResource]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class ListDataCenters(_serialization.Model): - """List of managed Cassandra data centers and their properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: Container for array of data centers. - :vartype value: list[~azure.mgmt.cosmosdb.models.DataCenterResource] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[DataCenterResource]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class Location(_serialization.Model): - """A region in which the Azure Cosmos DB database account is deployed. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique identifier of the region within the database account. Example: - <accountName>-<locationName>. - :vartype id: str - :ivar location_name: The name of the region. - :vartype location_name: str - :ivar document_endpoint: The connection endpoint for the specific region. Example: - https://<accountName>-<locationName>.documents.azure.com:443/. - :vartype document_endpoint: str - :ivar provisioning_state: The status of the Cosmos DB account at the time the operation was - called. The status can be one of following. 'Creating' – the Cosmos DB account is being - created. When an account is in Creating state, only properties that are specified as input for - the Create Cosmos DB account operation are returned. 'Succeeded' – the Cosmos DB account is - active for use. 'Updating' – the Cosmos DB account is being updated. 'Deleting' – the Cosmos DB - account is being deleted. 'Failed' – the Cosmos DB account failed creation. 'DeletionFailed' – - the Cosmos DB account deletion failed. - :vartype provisioning_state: str - :ivar failover_priority: The failover priority of the region. A failover priority of 0 - indicates a write region. The maximum value for a failover priority = (total number of regions - - 1). Failover priority values must be unique for each of the regions in which the database - account exists. - :vartype failover_priority: int - :ivar is_zone_redundant: Flag to indicate whether or not this region is an AvailabilityZone - region. - :vartype is_zone_redundant: bool - """ - - _validation = { - "id": {"readonly": True}, - "document_endpoint": {"readonly": True}, - "provisioning_state": {"readonly": True}, - "failover_priority": {"minimum": 0}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "location_name": {"key": "locationName", "type": "str"}, - "document_endpoint": {"key": "documentEndpoint", "type": "str"}, - "provisioning_state": {"key": "provisioningState", "type": "str"}, - "failover_priority": {"key": "failoverPriority", "type": "int"}, - "is_zone_redundant": {"key": "isZoneRedundant", "type": "bool"}, - } - - def __init__( - self, - *, - location_name: Optional[str] = None, - failover_priority: Optional[int] = None, - is_zone_redundant: Optional[bool] = None, - **kwargs: Any - ) -> None: - """ - :keyword location_name: The name of the region. - :paramtype location_name: str - :keyword failover_priority: The failover priority of the region. A failover priority of 0 - indicates a write region. The maximum value for a failover priority = (total number of regions - - 1). Failover priority values must be unique for each of the regions in which the database - account exists. - :paramtype failover_priority: int - :keyword is_zone_redundant: Flag to indicate whether or not this region is an AvailabilityZone - region. - :paramtype is_zone_redundant: bool - """ - super().__init__(**kwargs) - self.id = None - self.location_name = location_name - self.document_endpoint = None - self.provisioning_state = None - self.failover_priority = failover_priority - self.is_zone_redundant = is_zone_redundant - - -class LocationGetResult(ARMProxyResource): - """Cosmos DB location get result. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the database account. - :vartype id: str - :ivar name: The name of the database account. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar properties: Cosmos DB location metadata. - :vartype properties: ~azure.mgmt.cosmosdb.models.LocationProperties - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "properties": {"key": "properties", "type": "LocationProperties"}, - } - - def __init__(self, *, properties: Optional["_models.LocationProperties"] = None, **kwargs: Any) -> None: - """ - :keyword properties: Cosmos DB location metadata. - :paramtype properties: ~azure.mgmt.cosmosdb.models.LocationProperties - """ - super().__init__(**kwargs) - self.properties = properties - - -class LocationListResult(_serialization.Model): - """The List operation response, that contains Cosmos DB locations and their properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of Cosmos DB locations and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.LocationGetResult] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[LocationGetResult]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class LocationProperties(_serialization.Model): - """Cosmos DB location metadata. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar supports_availability_zone: Flag indicating whether the location supports availability - zones or not. - :vartype supports_availability_zone: bool - :ivar is_residency_restricted: Flag indicating whether the location is residency sensitive. - :vartype is_residency_restricted: bool - :ivar backup_storage_redundancies: The properties of available backup storage redundancies. - :vartype backup_storage_redundancies: list[str or - ~azure.mgmt.cosmosdb.models.BackupStorageRedundancy] - :ivar is_subscription_region_access_allowed_for_regular: Flag indicating whether the - subscription have access in region for Non-Availability Zones. - :vartype is_subscription_region_access_allowed_for_regular: bool - :ivar is_subscription_region_access_allowed_for_az: Flag indicating whether the subscription - have access in region for Availability Zones(Az). - :vartype is_subscription_region_access_allowed_for_az: bool - :ivar status: Enum to indicate current buildout status of the region. Known values are: - "Uninitialized", "Initializing", "InternallyReady", "Online", "Deleting", "Succeeded", - "Failed", "Canceled", and "Updating". - :vartype status: str or ~azure.mgmt.cosmosdb.models.Status - """ - - _validation = { - "supports_availability_zone": {"readonly": True}, - "is_residency_restricted": {"readonly": True}, - "backup_storage_redundancies": {"readonly": True}, - "is_subscription_region_access_allowed_for_regular": {"readonly": True}, - "is_subscription_region_access_allowed_for_az": {"readonly": True}, - "status": {"readonly": True}, - } - - _attribute_map = { - "supports_availability_zone": {"key": "supportsAvailabilityZone", "type": "bool"}, - "is_residency_restricted": {"key": "isResidencyRestricted", "type": "bool"}, - "backup_storage_redundancies": {"key": "backupStorageRedundancies", "type": "[str]"}, - "is_subscription_region_access_allowed_for_regular": { - "key": "isSubscriptionRegionAccessAllowedForRegular", - "type": "bool", - }, - "is_subscription_region_access_allowed_for_az": { - "key": "isSubscriptionRegionAccessAllowedForAz", - "type": "bool", - }, - "status": {"key": "status", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.supports_availability_zone = None - self.is_residency_restricted = None - self.backup_storage_redundancies = None - self.is_subscription_region_access_allowed_for_regular = None - self.is_subscription_region_access_allowed_for_az = None - self.status = None - - -class ManagedCassandraManagedServiceIdentity(_serialization.Model): - """Identity for the resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar principal_id: The object id of the identity resource. - :vartype principal_id: str - :ivar tenant_id: The tenant id of the resource. - :vartype tenant_id: str - :ivar type: The type of the resource. Known values are: "SystemAssigned" and "None". - :vartype type: str or ~azure.mgmt.cosmosdb.models.ManagedCassandraResourceIdentityType - """ - - _validation = { - "principal_id": {"readonly": True}, - "tenant_id": {"readonly": True}, - } - - _attribute_map = { - "principal_id": {"key": "principalId", "type": "str"}, - "tenant_id": {"key": "tenantId", "type": "str"}, - "type": {"key": "type", "type": "str"}, - } - - def __init__( - self, *, type: Optional[Union[str, "_models.ManagedCassandraResourceIdentityType"]] = None, **kwargs: Any - ) -> None: - """ - :keyword type: The type of the resource. Known values are: "SystemAssigned" and "None". - :paramtype type: str or ~azure.mgmt.cosmosdb.models.ManagedCassandraResourceIdentityType - """ - super().__init__(**kwargs) - self.principal_id = None - self.tenant_id = None - self.type = type - - -class ManagedCassandraReaperStatus(_serialization.Model): - """ManagedCassandraReaperStatus. - - :ivar healthy: - :vartype healthy: bool - :ivar repair_run_ids: Dictionary of :code:``. - :vartype repair_run_ids: dict[str, str] - :ivar repair_schedules: Dictionary of :code:``. - :vartype repair_schedules: dict[str, str] - """ - - _attribute_map = { - "healthy": {"key": "healthy", "type": "bool"}, - "repair_run_ids": {"key": "repairRunIds", "type": "{str}"}, - "repair_schedules": {"key": "repairSchedules", "type": "{str}"}, - } - - def __init__( - self, - *, - healthy: Optional[bool] = None, - repair_run_ids: Optional[Dict[str, str]] = None, - repair_schedules: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> None: - """ - :keyword healthy: - :paramtype healthy: bool - :keyword repair_run_ids: Dictionary of :code:``. - :paramtype repair_run_ids: dict[str, str] - :keyword repair_schedules: Dictionary of :code:``. - :paramtype repair_schedules: dict[str, str] - """ - super().__init__(**kwargs) - self.healthy = healthy - self.repair_run_ids = repair_run_ids - self.repair_schedules = repair_schedules - - -class ManagedServiceIdentity(_serialization.Model): - """Identity for the resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar principal_id: The principal id of the system assigned identity. This property will only - be provided for a system assigned identity. - :vartype principal_id: str - :ivar tenant_id: The tenant id of the system assigned identity. This property will only be - provided for a system assigned identity. - :vartype tenant_id: str - :ivar type: The type of identity used for the resource. The type 'SystemAssigned,UserAssigned' - includes both an implicitly created identity and a set of user assigned identities. The type - 'None' will remove any identities from the service. Known values are: "SystemAssigned", - "UserAssigned", "SystemAssigned,UserAssigned", and "None". - :vartype type: str or ~azure.mgmt.cosmosdb.models.ResourceIdentityType - :ivar user_assigned_identities: The list of user identities associated with resource. The user - identity dictionary key references will be ARM resource ids in the form: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. # pylint: disable=line-too-long - :vartype user_assigned_identities: dict[str, - ~azure.mgmt.cosmosdb.models.ManagedServiceIdentityUserAssignedIdentity] - """ - - _validation = { - "principal_id": {"readonly": True}, - "tenant_id": {"readonly": True}, - } - - _attribute_map = { - "principal_id": {"key": "principalId", "type": "str"}, - "tenant_id": {"key": "tenantId", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "user_assigned_identities": { - "key": "userAssignedIdentities", - "type": "{ManagedServiceIdentityUserAssignedIdentity}", - }, - } - - def __init__( - self, - *, - type: Optional[Union[str, "_models.ResourceIdentityType"]] = None, - user_assigned_identities: Optional[Dict[str, "_models.ManagedServiceIdentityUserAssignedIdentity"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword type: The type of identity used for the resource. The type - 'SystemAssigned,UserAssigned' includes both an implicitly created identity and a set of user - assigned identities. The type 'None' will remove any identities from the service. Known values - are: "SystemAssigned", "UserAssigned", "SystemAssigned,UserAssigned", and "None". - :paramtype type: str or ~azure.mgmt.cosmosdb.models.ResourceIdentityType - :keyword user_assigned_identities: The list of user identities associated with resource. The - user identity dictionary key references will be ARM resource ids in the form: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. # pylint: disable=line-too-long - :paramtype user_assigned_identities: dict[str, - ~azure.mgmt.cosmosdb.models.ManagedServiceIdentityUserAssignedIdentity] - """ - super().__init__(**kwargs) - self.principal_id = None - self.tenant_id = None - self.type = type - self.user_assigned_identities = user_assigned_identities - - -class ManagedServiceIdentityUserAssignedIdentity(_serialization.Model): # pylint: disable=name-too-long - """ManagedServiceIdentityUserAssignedIdentity. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar principal_id: The principal id of user assigned identity. - :vartype principal_id: str - :ivar client_id: The client id of user assigned identity. - :vartype client_id: str - """ - - _validation = { - "principal_id": {"readonly": True}, - "client_id": {"readonly": True}, - } - - _attribute_map = { - "principal_id": {"key": "principalId", "type": "str"}, - "client_id": {"key": "clientId", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.principal_id = None - self.client_id = None - - -class MaterializedViewDefinition(_serialization.Model): - """Materialized View definition for the container. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar source_collection_rid: An unique identifier for the source collection. This is a system - generated property. - :vartype source_collection_rid: str - :ivar source_collection_id: The name of the source container on which the Materialized View - will be created. Required. - :vartype source_collection_id: str - :ivar definition: The definition should be an SQL query which would be used to fetch data from - the source container to populate into the Materialized View container. Required. - :vartype definition: str - """ - - _validation = { - "source_collection_rid": {"readonly": True}, - "source_collection_id": {"required": True}, - "definition": {"required": True}, - } - - _attribute_map = { - "source_collection_rid": {"key": "sourceCollectionRid", "type": "str"}, - "source_collection_id": {"key": "sourceCollectionId", "type": "str"}, - "definition": {"key": "definition", "type": "str"}, - } - - def __init__(self, *, source_collection_id: str, definition: str, **kwargs: Any) -> None: - """ - :keyword source_collection_id: The name of the source container on which the Materialized View - will be created. Required. - :paramtype source_collection_id: str - :keyword definition: The definition should be an SQL query which would be used to fetch data - from the source container to populate into the Materialized View container. Required. - :paramtype definition: str - """ - super().__init__(**kwargs) - self.source_collection_rid = None - self.source_collection_id = source_collection_id - self.definition = definition - - -class MaterializedViewsBuilderRegionalServiceResource(RegionalServiceResource): # pylint: disable=name-too-long - """Resource for a regional service location. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar name: The regional service name. - :vartype name: str - :ivar location: The location name. - :vartype location: str - :ivar status: Describes the status of a service. Known values are: "Creating", "Running", - "Updating", "Deleting", "Error", and "Stopped". - :vartype status: str or ~azure.mgmt.cosmosdb.models.ServiceStatus - """ - - -class MaterializedViewsBuilderServiceResource(_serialization.Model): - """Describes the service response property for MaterializedViewsBuilder. - - :ivar properties: Properties for MaterializedViewsBuilderServiceResource. - :vartype properties: - ~azure.mgmt.cosmosdb.models.MaterializedViewsBuilderServiceResourceProperties - """ - - _attribute_map = { - "properties": {"key": "properties", "type": "MaterializedViewsBuilderServiceResourceProperties"}, - } - - def __init__( - self, *, properties: Optional["_models.MaterializedViewsBuilderServiceResourceProperties"] = None, **kwargs: Any - ) -> None: - """ - :keyword properties: Properties for MaterializedViewsBuilderServiceResource. - :paramtype properties: - ~azure.mgmt.cosmosdb.models.MaterializedViewsBuilderServiceResourceProperties - """ - super().__init__(**kwargs) - self.properties = properties - - -class MaterializedViewsBuilderServiceResourceCreateUpdateProperties( - ServiceResourceCreateUpdateProperties -): # pylint: disable=name-too-long - """Properties for Create or Update request for MaterializedViewsBuilderServiceResource. - - All required parameters must be populated in order to send to server. - - :ivar instance_size: Instance type for the service. Known values are: "Cosmos.D4s", - "Cosmos.D8s", and "Cosmos.D16s". - :vartype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize - :ivar instance_count: Instance count for the service. - :vartype instance_count: int - :ivar service_type: ServiceType for the service. Required. Known values are: - "SqlDedicatedGateway", "DataTransfer", "GraphAPICompute", and "MaterializedViewsBuilder". - :vartype service_type: str or ~azure.mgmt.cosmosdb.models.ServiceType - """ - - _validation = { - "instance_count": {"minimum": 0}, - "service_type": {"required": True}, - } - - _attribute_map = { - "instance_size": {"key": "instanceSize", "type": "str"}, - "instance_count": {"key": "instanceCount", "type": "int"}, - "service_type": {"key": "serviceType", "type": "str"}, - } - - def __init__( - self, - *, - instance_size: Optional[Union[str, "_models.ServiceSize"]] = None, - instance_count: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword instance_size: Instance type for the service. Known values are: "Cosmos.D4s", - "Cosmos.D8s", and "Cosmos.D16s". - :paramtype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize - :keyword instance_count: Instance count for the service. - :paramtype instance_count: int - """ - super().__init__(instance_size=instance_size, instance_count=instance_count, **kwargs) - self.service_type: str = "MaterializedViewsBuilder" - - -class MaterializedViewsBuilderServiceResourceProperties(ServiceResourceProperties): # pylint: disable=name-too-long - """Properties for MaterializedViewsBuilderServiceResource. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar additional_properties: Unmatched properties from the message are deserialized to this - collection. - :vartype additional_properties: dict[str, any] - :ivar creation_time: Time of the last state change (ISO-8601 format). - :vartype creation_time: ~datetime.datetime - :ivar instance_size: Instance type for the service. Known values are: "Cosmos.D4s", - "Cosmos.D8s", and "Cosmos.D16s". - :vartype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize - :ivar instance_count: Instance count for the service. - :vartype instance_count: int - :ivar service_type: ServiceType for the service. Required. Known values are: - "SqlDedicatedGateway", "DataTransfer", "GraphAPICompute", and "MaterializedViewsBuilder". - :vartype service_type: str or ~azure.mgmt.cosmosdb.models.ServiceType - :ivar status: Describes the status of a service. Known values are: "Creating", "Running", - "Updating", "Deleting", "Error", and "Stopped". - :vartype status: str or ~azure.mgmt.cosmosdb.models.ServiceStatus - :ivar locations: An array that contains all of the locations for the service. - :vartype locations: - list[~azure.mgmt.cosmosdb.models.MaterializedViewsBuilderRegionalServiceResource] - """ - - _validation = { - "creation_time": {"readonly": True}, - "instance_count": {"minimum": 0}, - "service_type": {"required": True}, - "status": {"readonly": True}, - "locations": {"readonly": True}, - } - - _attribute_map = { - "additional_properties": {"key": "", "type": "{object}"}, - "creation_time": {"key": "creationTime", "type": "iso-8601"}, - "instance_size": {"key": "instanceSize", "type": "str"}, - "instance_count": {"key": "instanceCount", "type": "int"}, - "service_type": {"key": "serviceType", "type": "str"}, - "status": {"key": "status", "type": "str"}, - "locations": {"key": "locations", "type": "[MaterializedViewsBuilderRegionalServiceResource]"}, - } - - def __init__( - self, - *, - additional_properties: Optional[Dict[str, Any]] = None, - instance_size: Optional[Union[str, "_models.ServiceSize"]] = None, - instance_count: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword additional_properties: Unmatched properties from the message are deserialized to this - collection. - :paramtype additional_properties: dict[str, any] - :keyword instance_size: Instance type for the service. Known values are: "Cosmos.D4s", - "Cosmos.D8s", and "Cosmos.D16s". - :paramtype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize - :keyword instance_count: Instance count for the service. - :paramtype instance_count: int - """ - super().__init__( - additional_properties=additional_properties, - instance_size=instance_size, - instance_count=instance_count, - **kwargs - ) - self.service_type: str = "MaterializedViewsBuilder" - self.locations = None - - -class MergeParameters(_serialization.Model): - """The properties of an Azure Cosmos DB merge operations. - - :ivar is_dry_run: Specifies whether the operation is a real merge operation or a simulation. - :vartype is_dry_run: bool - """ - - _attribute_map = { - "is_dry_run": {"key": "isDryRun", "type": "bool"}, - } - - def __init__(self, *, is_dry_run: Optional[bool] = None, **kwargs: Any) -> None: - """ - :keyword is_dry_run: Specifies whether the operation is a real merge operation or a simulation. - :paramtype is_dry_run: bool - """ - super().__init__(**kwargs) - self.is_dry_run = is_dry_run - - -class Metric(_serialization.Model): - """Metric data. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar start_time: The start time for the metric (ISO-8601 format). - :vartype start_time: ~datetime.datetime - :ivar end_time: The end time for the metric (ISO-8601 format). - :vartype end_time: ~datetime.datetime - :ivar time_grain: The time grain to be used to summarize the metric values. - :vartype time_grain: str - :ivar unit: The unit of the metric. Known values are: "Count", "Bytes", "Seconds", "Percent", - "CountPerSecond", "BytesPerSecond", and "Milliseconds". - :vartype unit: str or ~azure.mgmt.cosmosdb.models.UnitType - :ivar name: The name information for the metric. - :vartype name: ~azure.mgmt.cosmosdb.models.MetricName - :ivar metric_values: The metric values for the specified time window and timestep. - :vartype metric_values: list[~azure.mgmt.cosmosdb.models.MetricValue] - """ - - _validation = { - "start_time": {"readonly": True}, - "end_time": {"readonly": True}, - "time_grain": {"readonly": True}, - "unit": {"readonly": True}, - "name": {"readonly": True}, - "metric_values": {"readonly": True}, - } - - _attribute_map = { - "start_time": {"key": "startTime", "type": "iso-8601"}, - "end_time": {"key": "endTime", "type": "iso-8601"}, - "time_grain": {"key": "timeGrain", "type": "str"}, - "unit": {"key": "unit", "type": "str"}, - "name": {"key": "name", "type": "MetricName"}, - "metric_values": {"key": "metricValues", "type": "[MetricValue]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.start_time = None - self.end_time = None - self.time_grain = None - self.unit = None - self.name = None - self.metric_values = None - - -class MetricAvailability(_serialization.Model): - """The availability of the metric. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar time_grain: The time grain to be used to summarize the metric values. - :vartype time_grain: str - :ivar retention: The retention for the metric values. - :vartype retention: str - """ - - _validation = { - "time_grain": {"readonly": True}, - "retention": {"readonly": True}, - } - - _attribute_map = { - "time_grain": {"key": "timeGrain", "type": "str"}, - "retention": {"key": "retention", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.time_grain = None - self.retention = None - - -class MetricDefinition(_serialization.Model): - """The definition of a metric. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar metric_availabilities: The list of metric availabilities for the account. - :vartype metric_availabilities: list[~azure.mgmt.cosmosdb.models.MetricAvailability] - :ivar primary_aggregation_type: The primary aggregation type of the metric. Known values are: - "None", "Average", "Total", "Minimum", "Maximum", and "Last". - :vartype primary_aggregation_type: str or ~azure.mgmt.cosmosdb.models.PrimaryAggregationType - :ivar unit: The unit of the metric. Known values are: "Count", "Bytes", "Seconds", "Percent", - "CountPerSecond", "BytesPerSecond", and "Milliseconds". - :vartype unit: str or ~azure.mgmt.cosmosdb.models.UnitType - :ivar resource_uri: The resource uri of the database. - :vartype resource_uri: str - :ivar name: The name information for the metric. - :vartype name: ~azure.mgmt.cosmosdb.models.MetricName - """ - - _validation = { - "metric_availabilities": {"readonly": True}, - "primary_aggregation_type": {"readonly": True}, - "unit": {"readonly": True}, - "resource_uri": {"readonly": True}, - "name": {"readonly": True}, - } - - _attribute_map = { - "metric_availabilities": {"key": "metricAvailabilities", "type": "[MetricAvailability]"}, - "primary_aggregation_type": {"key": "primaryAggregationType", "type": "str"}, - "unit": {"key": "unit", "type": "str"}, - "resource_uri": {"key": "resourceUri", "type": "str"}, - "name": {"key": "name", "type": "MetricName"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.metric_availabilities = None - self.primary_aggregation_type = None - self.unit = None - self.resource_uri = None - self.name = None - - -class MetricDefinitionsListResult(_serialization.Model): - """The response to a list metric definitions request. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of metric definitions for the account. - :vartype value: list[~azure.mgmt.cosmosdb.models.MetricDefinition] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[MetricDefinition]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class MetricListResult(_serialization.Model): - """The response to a list metrics request. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of metrics for the account. - :vartype value: list[~azure.mgmt.cosmosdb.models.Metric] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[Metric]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class MetricName(_serialization.Model): - """A metric name. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The name of the metric. - :vartype value: str - :ivar localized_value: The friendly name of the metric. - :vartype localized_value: str - """ - - _validation = { - "value": {"readonly": True}, - "localized_value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "str"}, - "localized_value": {"key": "localizedValue", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - self.localized_value = None - - -class MetricValue(_serialization.Model): - """Represents metrics values. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar count: The number of values for the metric. - :vartype count: int - :ivar average: The average value of the metric. - :vartype average: float - :ivar maximum: The max value of the metric. - :vartype maximum: float - :ivar minimum: The min value of the metric. - :vartype minimum: float - :ivar timestamp: The metric timestamp (ISO-8601 format). - :vartype timestamp: ~datetime.datetime - :ivar total: The total value of the metric. - :vartype total: float - """ - - _validation = { - "count": {"readonly": True}, - "average": {"readonly": True}, - "maximum": {"readonly": True}, - "minimum": {"readonly": True}, - "timestamp": {"readonly": True}, - "total": {"readonly": True}, - } - - _attribute_map = { - "count": {"key": "_count", "type": "int"}, - "average": {"key": "average", "type": "float"}, - "maximum": {"key": "maximum", "type": "float"}, - "minimum": {"key": "minimum", "type": "float"}, - "timestamp": {"key": "timestamp", "type": "iso-8601"}, - "total": {"key": "total", "type": "float"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.count = None - self.average = None - self.maximum = None - self.minimum = None - self.timestamp = None - self.total = None - - -class MongoDBCollectionCreateUpdateParameters(ARMResourceProperties): - """Parameters to create and update Cosmos DB MongoDB collection. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: The standard JSON format of a MongoDB collection. Required. - :vartype resource: ~azure.mgmt.cosmosdb.models.MongoDBCollectionResource - :ivar options: A key-value pair of options to be applied for the request. This corresponds to - the headers sent with the request. - :vartype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "resource": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "MongoDBCollectionResource"}, - "options": {"key": "properties.options", "type": "CreateUpdateOptions"}, - } - - def __init__( - self, - *, - resource: "_models.MongoDBCollectionResource", - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - options: Optional["_models.CreateUpdateOptions"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: The standard JSON format of a MongoDB collection. Required. - :paramtype resource: ~azure.mgmt.cosmosdb.models.MongoDBCollectionResource - :keyword options: A key-value pair of options to be applied for the request. This corresponds - to the headers sent with the request. - :paramtype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - self.options = options - - -class MongoDBCollectionGetPropertiesOptions(OptionsResource): - """MongoDBCollectionGetPropertiesOptions. - - :ivar throughput: Value of the Cosmos DB resource throughput or autoscaleSettings. Use the - ThroughputSetting resource when retrieving offer details. - :vartype throughput: int - :ivar autoscale_settings: Specifies the Autoscale settings. - :vartype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettings - """ - - -class MongoDBCollectionResource(_serialization.Model): - """Cosmos DB MongoDB collection resource object. - - All required parameters must be populated in order to send to server. - - :ivar id: Name of the Cosmos DB MongoDB collection. Required. - :vartype id: str - :ivar shard_key: A key-value pair of shard keys to be applied for the request. - :vartype shard_key: dict[str, str] - :ivar indexes: List of index keys. - :vartype indexes: list[~azure.mgmt.cosmosdb.models.MongoIndex] - :ivar analytical_storage_ttl: Analytical TTL. - :vartype analytical_storage_ttl: int - :ivar restore_parameters: Parameters to indicate the information about the restore. - :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" - and "Restore". - :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - """ - - _validation = { - "id": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "shard_key": {"key": "shardKey", "type": "{str}"}, - "indexes": {"key": "indexes", "type": "[MongoIndex]"}, - "analytical_storage_ttl": {"key": "analyticalStorageTtl", "type": "int"}, - "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, - "create_mode": {"key": "createMode", "type": "str"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - shard_key: Optional[Dict[str, str]] = None, - indexes: Optional[List["_models.MongoIndex"]] = None, - analytical_storage_ttl: Optional[int] = None, - restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, - create_mode: Union[str, "_models.CreateMode"] = "Default", - **kwargs: Any - ) -> None: - """ - :keyword id: Name of the Cosmos DB MongoDB collection. Required. - :paramtype id: str - :keyword shard_key: A key-value pair of shard keys to be applied for the request. - :paramtype shard_key: dict[str, str] - :keyword indexes: List of index keys. - :paramtype indexes: list[~azure.mgmt.cosmosdb.models.MongoIndex] - :keyword analytical_storage_ttl: Analytical TTL. - :paramtype analytical_storage_ttl: int - :keyword restore_parameters: Parameters to indicate the information about the restore. - :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: - "Default" and "Restore". - :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - """ - super().__init__(**kwargs) - self.id = id - self.shard_key = shard_key - self.indexes = indexes - self.analytical_storage_ttl = analytical_storage_ttl - self.restore_parameters = restore_parameters - self.create_mode = create_mode - - -class MongoDBCollectionGetPropertiesResource(MongoDBCollectionResource, ExtendedResourceProperties): - """MongoDBCollectionGetPropertiesResource. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar rid: A system generated property. A unique identifier. - :vartype rid: str - :ivar ts: A system generated property that denotes the last updated timestamp of the resource. - :vartype ts: float - :ivar etag: A system generated property representing the resource etag required for optimistic - concurrency control. - :vartype etag: str - :ivar id: Name of the Cosmos DB MongoDB collection. Required. - :vartype id: str - :ivar shard_key: A key-value pair of shard keys to be applied for the request. - :vartype shard_key: dict[str, str] - :ivar indexes: List of index keys. - :vartype indexes: list[~azure.mgmt.cosmosdb.models.MongoIndex] - :ivar analytical_storage_ttl: Analytical TTL. - :vartype analytical_storage_ttl: int - :ivar restore_parameters: Parameters to indicate the information about the restore. - :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" - and "Restore". - :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - """ - - _validation = { - "rid": {"readonly": True}, - "ts": {"readonly": True}, - "etag": {"readonly": True}, - "id": {"required": True}, - } - - _attribute_map = { - "rid": {"key": "_rid", "type": "str"}, - "ts": {"key": "_ts", "type": "float"}, - "etag": {"key": "_etag", "type": "str"}, - "id": {"key": "id", "type": "str"}, - "shard_key": {"key": "shardKey", "type": "{str}"}, - "indexes": {"key": "indexes", "type": "[MongoIndex]"}, - "analytical_storage_ttl": {"key": "analyticalStorageTtl", "type": "int"}, - "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, - "create_mode": {"key": "createMode", "type": "str"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - shard_key: Optional[Dict[str, str]] = None, - indexes: Optional[List["_models.MongoIndex"]] = None, - analytical_storage_ttl: Optional[int] = None, - restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, - create_mode: Union[str, "_models.CreateMode"] = "Default", - **kwargs: Any - ) -> None: - """ - :keyword id: Name of the Cosmos DB MongoDB collection. Required. - :paramtype id: str - :keyword shard_key: A key-value pair of shard keys to be applied for the request. - :paramtype shard_key: dict[str, str] - :keyword indexes: List of index keys. - :paramtype indexes: list[~azure.mgmt.cosmosdb.models.MongoIndex] - :keyword analytical_storage_ttl: Analytical TTL. - :paramtype analytical_storage_ttl: int - :keyword restore_parameters: Parameters to indicate the information about the restore. - :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: - "Default" and "Restore". - :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - """ - super().__init__( - id=id, - shard_key=shard_key, - indexes=indexes, - analytical_storage_ttl=analytical_storage_ttl, - restore_parameters=restore_parameters, - create_mode=create_mode, - **kwargs - ) - self.rid = None - self.ts = None - self.etag = None - self.id = id - self.shard_key = shard_key - self.indexes = indexes - self.analytical_storage_ttl = analytical_storage_ttl - self.restore_parameters = restore_parameters - self.create_mode = create_mode - - -class MongoDBCollectionGetResults(ARMResourceProperties): - """An Azure Cosmos DB MongoDB collection. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: - :vartype resource: ~azure.mgmt.cosmosdb.models.MongoDBCollectionGetPropertiesResource - :ivar options: - :vartype options: ~azure.mgmt.cosmosdb.models.MongoDBCollectionGetPropertiesOptions - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "MongoDBCollectionGetPropertiesResource"}, - "options": {"key": "properties.options", "type": "MongoDBCollectionGetPropertiesOptions"}, - } - - def __init__( - self, - *, - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - resource: Optional["_models.MongoDBCollectionGetPropertiesResource"] = None, - options: Optional["_models.MongoDBCollectionGetPropertiesOptions"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: - :paramtype resource: ~azure.mgmt.cosmosdb.models.MongoDBCollectionGetPropertiesResource - :keyword options: - :paramtype options: ~azure.mgmt.cosmosdb.models.MongoDBCollectionGetPropertiesOptions - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - self.options = options - - -class MongoDBCollectionListResult(_serialization.Model): - """The List operation response, that contains the MongoDB collections and their properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of MongoDB collections and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.MongoDBCollectionGetResults] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[MongoDBCollectionGetResults]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class MongoDBDatabaseCreateUpdateParameters(ARMResourceProperties): - """Parameters to create and update Cosmos DB MongoDB database. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: The standard JSON format of a MongoDB database. Required. - :vartype resource: ~azure.mgmt.cosmosdb.models.MongoDBDatabaseResource - :ivar options: A key-value pair of options to be applied for the request. This corresponds to - the headers sent with the request. - :vartype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "resource": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "MongoDBDatabaseResource"}, - "options": {"key": "properties.options", "type": "CreateUpdateOptions"}, - } - - def __init__( - self, - *, - resource: "_models.MongoDBDatabaseResource", - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - options: Optional["_models.CreateUpdateOptions"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: The standard JSON format of a MongoDB database. Required. - :paramtype resource: ~azure.mgmt.cosmosdb.models.MongoDBDatabaseResource - :keyword options: A key-value pair of options to be applied for the request. This corresponds - to the headers sent with the request. - :paramtype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - self.options = options - - -class MongoDBDatabaseGetPropertiesOptions(OptionsResource): - """MongoDBDatabaseGetPropertiesOptions. - - :ivar throughput: Value of the Cosmos DB resource throughput or autoscaleSettings. Use the - ThroughputSetting resource when retrieving offer details. - :vartype throughput: int - :ivar autoscale_settings: Specifies the Autoscale settings. - :vartype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettings - """ - - -class MongoDBDatabaseResource(_serialization.Model): - """Cosmos DB MongoDB database resource object. - - All required parameters must be populated in order to send to server. - - :ivar id: Name of the Cosmos DB MongoDB database. Required. - :vartype id: str - :ivar restore_parameters: Parameters to indicate the information about the restore. - :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" - and "Restore". - :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - """ - - _validation = { - "id": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, - "create_mode": {"key": "createMode", "type": "str"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, - create_mode: Union[str, "_models.CreateMode"] = "Default", - **kwargs: Any - ) -> None: - """ - :keyword id: Name of the Cosmos DB MongoDB database. Required. - :paramtype id: str - :keyword restore_parameters: Parameters to indicate the information about the restore. - :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: - "Default" and "Restore". - :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - """ - super().__init__(**kwargs) - self.id = id - self.restore_parameters = restore_parameters - self.create_mode = create_mode - - -class MongoDBDatabaseGetPropertiesResource(MongoDBDatabaseResource, ExtendedResourceProperties): - """MongoDBDatabaseGetPropertiesResource. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar rid: A system generated property. A unique identifier. - :vartype rid: str - :ivar ts: A system generated property that denotes the last updated timestamp of the resource. - :vartype ts: float - :ivar etag: A system generated property representing the resource etag required for optimistic - concurrency control. - :vartype etag: str - :ivar id: Name of the Cosmos DB MongoDB database. Required. - :vartype id: str - :ivar restore_parameters: Parameters to indicate the information about the restore. - :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" - and "Restore". - :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - """ - - _validation = { - "rid": {"readonly": True}, - "ts": {"readonly": True}, - "etag": {"readonly": True}, - "id": {"required": True}, - } - - _attribute_map = { - "rid": {"key": "_rid", "type": "str"}, - "ts": {"key": "_ts", "type": "float"}, - "etag": {"key": "_etag", "type": "str"}, - "id": {"key": "id", "type": "str"}, - "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, - "create_mode": {"key": "createMode", "type": "str"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, - create_mode: Union[str, "_models.CreateMode"] = "Default", - **kwargs: Any - ) -> None: - """ - :keyword id: Name of the Cosmos DB MongoDB database. Required. - :paramtype id: str - :keyword restore_parameters: Parameters to indicate the information about the restore. - :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: - "Default" and "Restore". - :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - """ - super().__init__(id=id, restore_parameters=restore_parameters, create_mode=create_mode, **kwargs) - self.rid = None - self.ts = None - self.etag = None - self.id = id - self.restore_parameters = restore_parameters - self.create_mode = create_mode - - -class MongoDBDatabaseGetResults(ARMResourceProperties): - """An Azure Cosmos DB MongoDB database. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: - :vartype resource: ~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetPropertiesResource - :ivar options: - :vartype options: ~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetPropertiesOptions - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "MongoDBDatabaseGetPropertiesResource"}, - "options": {"key": "properties.options", "type": "MongoDBDatabaseGetPropertiesOptions"}, - } - - def __init__( - self, - *, - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - resource: Optional["_models.MongoDBDatabaseGetPropertiesResource"] = None, - options: Optional["_models.MongoDBDatabaseGetPropertiesOptions"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: - :paramtype resource: ~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetPropertiesResource - :keyword options: - :paramtype options: ~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetPropertiesOptions - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - self.options = options - - -class MongoDBDatabaseListResult(_serialization.Model): - """The List operation response, that contains the MongoDB databases and their properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of MongoDB databases and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetResults] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[MongoDBDatabaseGetResults]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class MongoIndex(_serialization.Model): - """Cosmos DB MongoDB collection index key. - - :ivar key: Cosmos DB MongoDB collection index keys. - :vartype key: ~azure.mgmt.cosmosdb.models.MongoIndexKeys - :ivar options: Cosmos DB MongoDB collection index key options. - :vartype options: ~azure.mgmt.cosmosdb.models.MongoIndexOptions - """ - - _attribute_map = { - "key": {"key": "key", "type": "MongoIndexKeys"}, - "options": {"key": "options", "type": "MongoIndexOptions"}, - } - - def __init__( - self, - *, - key: Optional["_models.MongoIndexKeys"] = None, - options: Optional["_models.MongoIndexOptions"] = None, - **kwargs: Any - ) -> None: - """ - :keyword key: Cosmos DB MongoDB collection index keys. - :paramtype key: ~azure.mgmt.cosmosdb.models.MongoIndexKeys - :keyword options: Cosmos DB MongoDB collection index key options. - :paramtype options: ~azure.mgmt.cosmosdb.models.MongoIndexOptions - """ - super().__init__(**kwargs) - self.key = key - self.options = options - - -class MongoIndexKeys(_serialization.Model): - """Cosmos DB MongoDB collection resource object. - - :ivar keys: List of keys for each MongoDB collection in the Azure Cosmos DB service. - :vartype keys: list[str] - """ - - _attribute_map = { - "keys": {"key": "keys", "type": "[str]"}, - } - - def __init__(self, *, keys: Optional[List[str]] = None, **kwargs: Any) -> None: - """ - :keyword keys: List of keys for each MongoDB collection in the Azure Cosmos DB service. - :paramtype keys: list[str] - """ - super().__init__(**kwargs) - self.keys = keys - - -class MongoIndexOptions(_serialization.Model): - """Cosmos DB MongoDB collection index options. - - :ivar expire_after_seconds: Expire after seconds. - :vartype expire_after_seconds: int - :ivar unique: Is unique or not. - :vartype unique: bool - """ - - _attribute_map = { - "expire_after_seconds": {"key": "expireAfterSeconds", "type": "int"}, - "unique": {"key": "unique", "type": "bool"}, - } - - def __init__( - self, *, expire_after_seconds: Optional[int] = None, unique: Optional[bool] = None, **kwargs: Any - ) -> None: - """ - :keyword expire_after_seconds: Expire after seconds. - :paramtype expire_after_seconds: int - :keyword unique: Is unique or not. - :paramtype unique: bool - """ - super().__init__(**kwargs) - self.expire_after_seconds = expire_after_seconds - self.unique = unique - - -class MongoRoleDefinitionCreateUpdateParameters(_serialization.Model): # pylint: disable=name-too-long - """Parameters to create and update an Azure Cosmos DB Mongo Role Definition. - - :ivar role_name: A user-friendly name for the Role Definition. Must be unique for the database - account. - :vartype role_name: str - :ivar type: Indicates whether the Role Definition was built-in or user created. Known values - are: "BuiltInRole" and "CustomRole". - :vartype type: str or ~azure.mgmt.cosmosdb.models.MongoRoleDefinitionType - :ivar database_name: The database name for which access is being granted for this Role - Definition. - :vartype database_name: str - :ivar privileges: A set of privileges contained by the Role Definition. This will allow - application of this Role Definition on the entire database account or any underlying Database / - Collection. Scopes higher than Database are not enforceable as privilege. - :vartype privileges: list[~azure.mgmt.cosmosdb.models.Privilege] - :ivar roles: The set of roles inherited by this Role Definition. - :vartype roles: list[~azure.mgmt.cosmosdb.models.Role] - """ - - _attribute_map = { - "role_name": {"key": "properties.roleName", "type": "str"}, - "type": {"key": "properties.type", "type": "str"}, - "database_name": {"key": "properties.databaseName", "type": "str"}, - "privileges": {"key": "properties.privileges", "type": "[Privilege]"}, - "roles": {"key": "properties.roles", "type": "[Role]"}, - } - - def __init__( - self, - *, - role_name: Optional[str] = None, - type: Optional[Union[str, "_models.MongoRoleDefinitionType"]] = None, - database_name: Optional[str] = None, - privileges: Optional[List["_models.Privilege"]] = None, - roles: Optional[List["_models.Role"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword role_name: A user-friendly name for the Role Definition. Must be unique for the - database account. - :paramtype role_name: str - :keyword type: Indicates whether the Role Definition was built-in or user created. Known values - are: "BuiltInRole" and "CustomRole". - :paramtype type: str or ~azure.mgmt.cosmosdb.models.MongoRoleDefinitionType - :keyword database_name: The database name for which access is being granted for this Role - Definition. - :paramtype database_name: str - :keyword privileges: A set of privileges contained by the Role Definition. This will allow - application of this Role Definition on the entire database account or any underlying Database / - Collection. Scopes higher than Database are not enforceable as privilege. - :paramtype privileges: list[~azure.mgmt.cosmosdb.models.Privilege] - :keyword roles: The set of roles inherited by this Role Definition. - :paramtype roles: list[~azure.mgmt.cosmosdb.models.Role] - """ - super().__init__(**kwargs) - self.role_name = role_name - self.type = type - self.database_name = database_name - self.privileges = privileges - self.roles = roles - - -class MongoRoleDefinitionGetResults(ARMProxyResource): - """An Azure Cosmos DB Mongo Role Definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the database account. - :vartype id: str - :ivar name: The name of the database account. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar role_name: A user-friendly name for the Role Definition. Must be unique for the database - account. - :vartype role_name: str - :ivar type_properties_type: Indicates whether the Role Definition was built-in or user created. - Known values are: "BuiltInRole" and "CustomRole". - :vartype type_properties_type: str or ~azure.mgmt.cosmosdb.models.MongoRoleDefinitionType - :ivar database_name: The database name for which access is being granted for this Role - Definition. - :vartype database_name: str - :ivar privileges: A set of privileges contained by the Role Definition. This will allow - application of this Role Definition on the entire database account or any underlying Database / - Collection. Scopes higher than Database are not enforceable as privilege. - :vartype privileges: list[~azure.mgmt.cosmosdb.models.Privilege] - :ivar roles: The set of roles inherited by this Role Definition. - :vartype roles: list[~azure.mgmt.cosmosdb.models.Role] - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "role_name": {"key": "properties.roleName", "type": "str"}, - "type_properties_type": {"key": "properties.type", "type": "str"}, - "database_name": {"key": "properties.databaseName", "type": "str"}, - "privileges": {"key": "properties.privileges", "type": "[Privilege]"}, - "roles": {"key": "properties.roles", "type": "[Role]"}, - } - - def __init__( - self, - *, - role_name: Optional[str] = None, - type_properties_type: Optional[Union[str, "_models.MongoRoleDefinitionType"]] = None, - database_name: Optional[str] = None, - privileges: Optional[List["_models.Privilege"]] = None, - roles: Optional[List["_models.Role"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword role_name: A user-friendly name for the Role Definition. Must be unique for the - database account. - :paramtype role_name: str - :keyword type_properties_type: Indicates whether the Role Definition was built-in or user - created. Known values are: "BuiltInRole" and "CustomRole". - :paramtype type_properties_type: str or ~azure.mgmt.cosmosdb.models.MongoRoleDefinitionType - :keyword database_name: The database name for which access is being granted for this Role - Definition. - :paramtype database_name: str - :keyword privileges: A set of privileges contained by the Role Definition. This will allow - application of this Role Definition on the entire database account or any underlying Database / - Collection. Scopes higher than Database are not enforceable as privilege. - :paramtype privileges: list[~azure.mgmt.cosmosdb.models.Privilege] - :keyword roles: The set of roles inherited by this Role Definition. - :paramtype roles: list[~azure.mgmt.cosmosdb.models.Role] - """ - super().__init__(**kwargs) - self.role_name = role_name - self.type_properties_type = type_properties_type - self.database_name = database_name - self.privileges = privileges - self.roles = roles - - -class MongoRoleDefinitionListResult(_serialization.Model): - """The relevant Mongo Role Definitions. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of Mongo Role Definitions and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.MongoRoleDefinitionGetResults] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[MongoRoleDefinitionGetResults]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class MongoUserDefinitionCreateUpdateParameters(_serialization.Model): # pylint: disable=name-too-long - """Parameters to create and update an Azure Cosmos DB Mongo User Definition. - - :ivar user_name: The user name for User Definition. - :vartype user_name: str - :ivar password: The password for User Definition. Response does not contain user password. - :vartype password: str - :ivar database_name: The database name for which access is being granted for this User - Definition. - :vartype database_name: str - :ivar custom_data: A custom definition for the USer Definition. - :vartype custom_data: str - :ivar roles: The set of roles inherited by the User Definition. - :vartype roles: list[~azure.mgmt.cosmosdb.models.Role] - :ivar mechanisms: The Mongo Auth mechanism. For now, we only support auth mechanism - SCRAM-SHA-256. - :vartype mechanisms: str - """ - - _attribute_map = { - "user_name": {"key": "properties.userName", "type": "str"}, - "password": {"key": "properties.password", "type": "str"}, - "database_name": {"key": "properties.databaseName", "type": "str"}, - "custom_data": {"key": "properties.customData", "type": "str"}, - "roles": {"key": "properties.roles", "type": "[Role]"}, - "mechanisms": {"key": "properties.mechanisms", "type": "str"}, - } - - def __init__( - self, - *, - user_name: Optional[str] = None, - password: Optional[str] = None, - database_name: Optional[str] = None, - custom_data: Optional[str] = None, - roles: Optional[List["_models.Role"]] = None, - mechanisms: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword user_name: The user name for User Definition. - :paramtype user_name: str - :keyword password: The password for User Definition. Response does not contain user password. - :paramtype password: str - :keyword database_name: The database name for which access is being granted for this User - Definition. - :paramtype database_name: str - :keyword custom_data: A custom definition for the USer Definition. - :paramtype custom_data: str - :keyword roles: The set of roles inherited by the User Definition. - :paramtype roles: list[~azure.mgmt.cosmosdb.models.Role] - :keyword mechanisms: The Mongo Auth mechanism. For now, we only support auth mechanism - SCRAM-SHA-256. - :paramtype mechanisms: str - """ - super().__init__(**kwargs) - self.user_name = user_name - self.password = password - self.database_name = database_name - self.custom_data = custom_data - self.roles = roles - self.mechanisms = mechanisms - - -class MongoUserDefinitionGetResults(ARMProxyResource): - """An Azure Cosmos DB User Definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the database account. - :vartype id: str - :ivar name: The name of the database account. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar user_name: The user name for User Definition. - :vartype user_name: str - :ivar password: The password for User Definition. Response does not contain user password. - :vartype password: str - :ivar database_name: The database name for which access is being granted for this User - Definition. - :vartype database_name: str - :ivar custom_data: A custom definition for the USer Definition. - :vartype custom_data: str - :ivar roles: The set of roles inherited by the User Definition. - :vartype roles: list[~azure.mgmt.cosmosdb.models.Role] - :ivar mechanisms: The Mongo Auth mechanism. For now, we only support auth mechanism - SCRAM-SHA-256. - :vartype mechanisms: str - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "user_name": {"key": "properties.userName", "type": "str"}, - "password": {"key": "properties.password", "type": "str"}, - "database_name": {"key": "properties.databaseName", "type": "str"}, - "custom_data": {"key": "properties.customData", "type": "str"}, - "roles": {"key": "properties.roles", "type": "[Role]"}, - "mechanisms": {"key": "properties.mechanisms", "type": "str"}, - } - - def __init__( - self, - *, - user_name: Optional[str] = None, - password: Optional[str] = None, - database_name: Optional[str] = None, - custom_data: Optional[str] = None, - roles: Optional[List["_models.Role"]] = None, - mechanisms: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword user_name: The user name for User Definition. - :paramtype user_name: str - :keyword password: The password for User Definition. Response does not contain user password. - :paramtype password: str - :keyword database_name: The database name for which access is being granted for this User - Definition. - :paramtype database_name: str - :keyword custom_data: A custom definition for the USer Definition. - :paramtype custom_data: str - :keyword roles: The set of roles inherited by the User Definition. - :paramtype roles: list[~azure.mgmt.cosmosdb.models.Role] - :keyword mechanisms: The Mongo Auth mechanism. For now, we only support auth mechanism - SCRAM-SHA-256. - :paramtype mechanisms: str - """ - super().__init__(**kwargs) - self.user_name = user_name - self.password = password - self.database_name = database_name - self.custom_data = custom_data - self.roles = roles - self.mechanisms = mechanisms - - -class MongoUserDefinitionListResult(_serialization.Model): - """The relevant User Definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of User Definition and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.MongoUserDefinitionGetResults] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[MongoUserDefinitionGetResults]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class NetworkSecurityPerimeter(_serialization.Model): - """Information about a network security perimeter (NSP). - - :ivar id: Fully qualified Azure resource ID of the NSP resource. - :vartype id: str - :ivar perimeter_guid: Universal unique ID (UUID) of the network security perimeter. - :vartype perimeter_guid: str - :ivar location: Location of the network security perimeter. - :vartype location: str - """ - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "perimeter_guid": {"key": "perimeterGuid", "type": "str"}, - "location": {"key": "location", "type": "str"}, - } - - def __init__( - self, - *, - id: Optional[str] = None, # pylint: disable=redefined-builtin - perimeter_guid: Optional[str] = None, - location: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: Fully qualified Azure resource ID of the NSP resource. - :paramtype id: str - :keyword perimeter_guid: Universal unique ID (UUID) of the network security perimeter. - :paramtype perimeter_guid: str - :keyword location: Location of the network security perimeter. - :paramtype location: str - """ - super().__init__(**kwargs) - self.id = id - self.perimeter_guid = perimeter_guid - self.location = location - - -class NetworkSecurityPerimeterConfiguration(ProxyResource): - """Network security perimeter (NSP) configuration resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Fully qualified resource ID for the resource. E.g. - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or - "Microsoft.Storage/storageAccounts". - :vartype type: str - :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy - information. - :vartype system_data: ~azure.mgmt.cosmosdb.models.SystemData - :ivar properties: Network security configuration properties. - :vartype properties: - ~azure.mgmt.cosmosdb.models.NetworkSecurityPerimeterConfigurationProperties - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "system_data": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "system_data": {"key": "systemData", "type": "SystemData"}, - "properties": {"key": "properties", "type": "NetworkSecurityPerimeterConfigurationProperties"}, - } - - def __init__( - self, *, properties: Optional["_models.NetworkSecurityPerimeterConfigurationProperties"] = None, **kwargs: Any - ) -> None: - """ - :keyword properties: Network security configuration properties. - :paramtype properties: - ~azure.mgmt.cosmosdb.models.NetworkSecurityPerimeterConfigurationProperties - """ - super().__init__(**kwargs) - self.properties = properties - - -class NetworkSecurityPerimeterConfigurationListResult(_serialization.Model): # pylint: disable=name-too-long - """Result of a list NSP (network security perimeter) configurations request. - - :ivar value: Array of network security perimeter results. - :vartype value: list[~azure.mgmt.cosmosdb.models.NetworkSecurityPerimeterConfiguration] - :ivar next_link: The link used to get the next page of results. - :vartype next_link: str - """ - - _attribute_map = { - "value": {"key": "value", "type": "[NetworkSecurityPerimeterConfiguration]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__( - self, - *, - value: Optional[List["_models.NetworkSecurityPerimeterConfiguration"]] = None, - next_link: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword value: Array of network security perimeter results. - :paramtype value: list[~azure.mgmt.cosmosdb.models.NetworkSecurityPerimeterConfiguration] - :keyword next_link: The link used to get the next page of results. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.value = value - self.next_link = next_link - - -class NetworkSecurityPerimeterConfigurationProperties(_serialization.Model): # pylint: disable=name-too-long - """Network security configuration properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar provisioning_state: Provisioning state of a network security perimeter configuration that - is being created or updated. Known values are: "Succeeded", "Creating", "Updating", "Deleting", - "Accepted", "Failed", and "Canceled". - :vartype provisioning_state: str or - ~azure.mgmt.cosmosdb.models.NetworkSecurityPerimeterConfigurationProvisioningState - :ivar provisioning_issues: List of provisioning issues, if any. - :vartype provisioning_issues: list[~azure.mgmt.cosmosdb.models.ProvisioningIssue] - :ivar network_security_perimeter: Information about a network security perimeter (NSP). - :vartype network_security_perimeter: ~azure.mgmt.cosmosdb.models.NetworkSecurityPerimeter - :ivar resource_association: Information about resource association. - :vartype resource_association: ~azure.mgmt.cosmosdb.models.ResourceAssociation - :ivar profile: Network security perimeter configuration profile. - :vartype profile: ~azure.mgmt.cosmosdb.models.NetworkSecurityProfile - """ - - _validation = { - "provisioning_state": {"readonly": True}, - "provisioning_issues": {"readonly": True}, - } - - _attribute_map = { - "provisioning_state": {"key": "provisioningState", "type": "str"}, - "provisioning_issues": {"key": "provisioningIssues", "type": "[ProvisioningIssue]"}, - "network_security_perimeter": {"key": "networkSecurityPerimeter", "type": "NetworkSecurityPerimeter"}, - "resource_association": {"key": "resourceAssociation", "type": "ResourceAssociation"}, - "profile": {"key": "profile", "type": "NetworkSecurityProfile"}, - } - - def __init__( - self, - *, - network_security_perimeter: Optional["_models.NetworkSecurityPerimeter"] = None, - resource_association: Optional["_models.ResourceAssociation"] = None, - profile: Optional["_models.NetworkSecurityProfile"] = None, - **kwargs: Any - ) -> None: - """ - :keyword network_security_perimeter: Information about a network security perimeter (NSP). - :paramtype network_security_perimeter: ~azure.mgmt.cosmosdb.models.NetworkSecurityPerimeter - :keyword resource_association: Information about resource association. - :paramtype resource_association: ~azure.mgmt.cosmosdb.models.ResourceAssociation - :keyword profile: Network security perimeter configuration profile. - :paramtype profile: ~azure.mgmt.cosmosdb.models.NetworkSecurityProfile - """ - super().__init__(**kwargs) - self.provisioning_state = None - self.provisioning_issues = None - self.network_security_perimeter = network_security_perimeter - self.resource_association = resource_association - self.profile = profile - - -class NetworkSecurityProfile(_serialization.Model): - """Network security perimeter configuration profile. - - :ivar name: Name of the profile. - :vartype name: str - :ivar access_rules_version: Current access rules version. - :vartype access_rules_version: int - :ivar access_rules: List of Access Rules. - :vartype access_rules: list[~azure.mgmt.cosmosdb.models.AccessRule] - :ivar diagnostic_settings_version: Current diagnostic settings version. - :vartype diagnostic_settings_version: int - :ivar enabled_log_categories: List of log categories that are enabled. - :vartype enabled_log_categories: list[str] - """ - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "access_rules_version": {"key": "accessRulesVersion", "type": "int"}, - "access_rules": {"key": "accessRules", "type": "[AccessRule]"}, - "diagnostic_settings_version": {"key": "diagnosticSettingsVersion", "type": "int"}, - "enabled_log_categories": {"key": "enabledLogCategories", "type": "[str]"}, - } - - def __init__( - self, - *, - name: Optional[str] = None, - access_rules_version: Optional[int] = None, - access_rules: Optional[List["_models.AccessRule"]] = None, - diagnostic_settings_version: Optional[int] = None, - enabled_log_categories: Optional[List[str]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: Name of the profile. - :paramtype name: str - :keyword access_rules_version: Current access rules version. - :paramtype access_rules_version: int - :keyword access_rules: List of Access Rules. - :paramtype access_rules: list[~azure.mgmt.cosmosdb.models.AccessRule] - :keyword diagnostic_settings_version: Current diagnostic settings version. - :paramtype diagnostic_settings_version: int - :keyword enabled_log_categories: List of log categories that are enabled. - :paramtype enabled_log_categories: list[str] - """ - super().__init__(**kwargs) - self.name = name - self.access_rules_version = access_rules_version - self.access_rules = access_rules - self.diagnostic_settings_version = diagnostic_settings_version - self.enabled_log_categories = enabled_log_categories - - -class NotebookWorkspace(ARMProxyResource): - """A notebook workspace resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the database account. - :vartype id: str - :ivar name: The name of the database account. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar notebook_server_endpoint: Specifies the endpoint of Notebook server. - :vartype notebook_server_endpoint: str - :ivar status: Status of the notebook workspace. Possible values are: Creating, Online, - Deleting, Failed, Updating. - :vartype status: str - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "notebook_server_endpoint": {"readonly": True}, - "status": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "notebook_server_endpoint": {"key": "properties.notebookServerEndpoint", "type": "str"}, - "status": {"key": "properties.status", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.notebook_server_endpoint = None - self.status = None - - -class NotebookWorkspaceConnectionInfoResult(_serialization.Model): - """The connection info for the given notebook workspace. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar auth_token: Specifies auth token used for connecting to Notebook server (uses token-based - auth). - :vartype auth_token: str - :ivar notebook_server_endpoint: Specifies the endpoint of Notebook server. - :vartype notebook_server_endpoint: str - """ - - _validation = { - "auth_token": {"readonly": True}, - "notebook_server_endpoint": {"readonly": True}, - } - - _attribute_map = { - "auth_token": {"key": "authToken", "type": "str"}, - "notebook_server_endpoint": {"key": "notebookServerEndpoint", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.auth_token = None - self.notebook_server_endpoint = None - - -class NotebookWorkspaceCreateUpdateParameters(ARMProxyResource): - """Parameters to create a notebook workspace resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the database account. - :vartype id: str - :ivar name: The name of the database account. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - """ - - -class NotebookWorkspaceListResult(_serialization.Model): - """A list of notebook workspace resources. - - :ivar value: Array of notebook workspace resources. - :vartype value: list[~azure.mgmt.cosmosdb.models.NotebookWorkspace] - """ - - _attribute_map = { - "value": {"key": "value", "type": "[NotebookWorkspace]"}, - } - - def __init__(self, *, value: Optional[List["_models.NotebookWorkspace"]] = None, **kwargs: Any) -> None: - """ - :keyword value: Array of notebook workspace resources. - :paramtype value: list[~azure.mgmt.cosmosdb.models.NotebookWorkspace] - """ - super().__init__(**kwargs) - self.value = value - - -class Operation(_serialization.Model): - """REST API operation. - - :ivar name: Operation name: {provider}/{resource}/{operation}. - :vartype name: str - :ivar display: The object that represents the operation. - :vartype display: ~azure.mgmt.cosmosdb.models.OperationDisplay - """ - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "display": {"key": "display", "type": "OperationDisplay"}, - } - - def __init__( - self, *, name: Optional[str] = None, display: Optional["_models.OperationDisplay"] = None, **kwargs: Any - ) -> None: - """ - :keyword name: Operation name: {provider}/{resource}/{operation}. - :paramtype name: str - :keyword display: The object that represents the operation. - :paramtype display: ~azure.mgmt.cosmosdb.models.OperationDisplay - """ - super().__init__(**kwargs) - self.name = name - self.display = display - - -class OperationDisplay(_serialization.Model): - """The object that represents the operation. - - :ivar provider: Service provider: Microsoft.ResourceProvider. - :vartype provider: str - :ivar resource: Resource on which the operation is performed: Profile, endpoint, etc. - :vartype resource: str - :ivar operation: Operation type: Read, write, delete, etc. - :vartype operation: str - :ivar description: Description of operation. - :vartype description: str - """ - - _attribute_map = { - "provider": {"key": "Provider", "type": "str"}, - "resource": {"key": "Resource", "type": "str"}, - "operation": {"key": "Operation", "type": "str"}, - "description": {"key": "Description", "type": "str"}, - } - - def __init__( - self, - *, - provider: Optional[str] = None, - resource: Optional[str] = None, - operation: Optional[str] = None, - description: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword provider: Service provider: Microsoft.ResourceProvider. - :paramtype provider: str - :keyword resource: Resource on which the operation is performed: Profile, endpoint, etc. - :paramtype resource: str - :keyword operation: Operation type: Read, write, delete, etc. - :paramtype operation: str - :keyword description: Description of operation. - :paramtype description: str - """ - super().__init__(**kwargs) - self.provider = provider - self.resource = resource - self.operation = operation - self.description = description - - -class OperationListResult(_serialization.Model): - """Result of the request to list Resource Provider operations. It contains a list of operations - and a URL link to get the next set of results. - - :ivar value: List of operations supported by the Resource Provider. - :vartype value: list[~azure.mgmt.cosmosdb.models.Operation] - :ivar next_link: URL to get the next set of operation list results if there are any. - :vartype next_link: str - """ - - _attribute_map = { - "value": {"key": "value", "type": "[Operation]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__( - self, *, value: Optional[List["_models.Operation"]] = None, next_link: Optional[str] = None, **kwargs: Any - ) -> None: - """ - :keyword value: List of operations supported by the Resource Provider. - :paramtype value: list[~azure.mgmt.cosmosdb.models.Operation] - :keyword next_link: URL to get the next set of operation list results if there are any. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.value = value - self.next_link = next_link - - -class PartitionMetric(Metric): - """The metric values for a single partition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar start_time: The start time for the metric (ISO-8601 format). - :vartype start_time: ~datetime.datetime - :ivar end_time: The end time for the metric (ISO-8601 format). - :vartype end_time: ~datetime.datetime - :ivar time_grain: The time grain to be used to summarize the metric values. - :vartype time_grain: str - :ivar unit: The unit of the metric. Known values are: "Count", "Bytes", "Seconds", "Percent", - "CountPerSecond", "BytesPerSecond", and "Milliseconds". - :vartype unit: str or ~azure.mgmt.cosmosdb.models.UnitType - :ivar name: The name information for the metric. - :vartype name: ~azure.mgmt.cosmosdb.models.MetricName - :ivar metric_values: The metric values for the specified time window and timestep. - :vartype metric_values: list[~azure.mgmt.cosmosdb.models.MetricValue] - :ivar partition_id: The partition id (GUID identifier) of the metric values. - :vartype partition_id: str - :ivar partition_key_range_id: The partition key range id (integer identifier) of the metric - values. - :vartype partition_key_range_id: str - """ - - _validation = { - "start_time": {"readonly": True}, - "end_time": {"readonly": True}, - "time_grain": {"readonly": True}, - "unit": {"readonly": True}, - "name": {"readonly": True}, - "metric_values": {"readonly": True}, - "partition_id": {"readonly": True}, - "partition_key_range_id": {"readonly": True}, - } - - _attribute_map = { - "start_time": {"key": "startTime", "type": "iso-8601"}, - "end_time": {"key": "endTime", "type": "iso-8601"}, - "time_grain": {"key": "timeGrain", "type": "str"}, - "unit": {"key": "unit", "type": "str"}, - "name": {"key": "name", "type": "MetricName"}, - "metric_values": {"key": "metricValues", "type": "[MetricValue]"}, - "partition_id": {"key": "partitionId", "type": "str"}, - "partition_key_range_id": {"key": "partitionKeyRangeId", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.partition_id = None - self.partition_key_range_id = None - - -class PartitionMetricListResult(_serialization.Model): - """The response to a list partition metrics request. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of partition-level metrics for the account. - :vartype value: list[~azure.mgmt.cosmosdb.models.PartitionMetric] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[PartitionMetric]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class Usage(_serialization.Model): - """The usage data for a usage request. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar unit: The unit of the metric. Known values are: "Count", "Bytes", "Seconds", "Percent", - "CountPerSecond", "BytesPerSecond", and "Milliseconds". - :vartype unit: str or ~azure.mgmt.cosmosdb.models.UnitType - :ivar name: The name information for the metric. - :vartype name: ~azure.mgmt.cosmosdb.models.MetricName - :ivar quota_period: The quota period used to summarize the usage values. - :vartype quota_period: str - :ivar limit: Maximum value for this metric. - :vartype limit: int - :ivar current_value: Current value for this metric. - :vartype current_value: int - """ - - _validation = { - "unit": {"readonly": True}, - "name": {"readonly": True}, - "quota_period": {"readonly": True}, - "limit": {"readonly": True}, - "current_value": {"readonly": True}, - } - - _attribute_map = { - "unit": {"key": "unit", "type": "str"}, - "name": {"key": "name", "type": "MetricName"}, - "quota_period": {"key": "quotaPeriod", "type": "str"}, - "limit": {"key": "limit", "type": "int"}, - "current_value": {"key": "currentValue", "type": "int"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.unit = None - self.name = None - self.quota_period = None - self.limit = None - self.current_value = None - - -class PartitionUsage(Usage): - """The partition level usage data for a usage request. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar unit: The unit of the metric. Known values are: "Count", "Bytes", "Seconds", "Percent", - "CountPerSecond", "BytesPerSecond", and "Milliseconds". - :vartype unit: str or ~azure.mgmt.cosmosdb.models.UnitType - :ivar name: The name information for the metric. - :vartype name: ~azure.mgmt.cosmosdb.models.MetricName - :ivar quota_period: The quota period used to summarize the usage values. - :vartype quota_period: str - :ivar limit: Maximum value for this metric. - :vartype limit: int - :ivar current_value: Current value for this metric. - :vartype current_value: int - :ivar partition_id: The partition id (GUID identifier) of the usages. - :vartype partition_id: str - :ivar partition_key_range_id: The partition key range id (integer identifier) of the usages. - :vartype partition_key_range_id: str - """ - - _validation = { - "unit": {"readonly": True}, - "name": {"readonly": True}, - "quota_period": {"readonly": True}, - "limit": {"readonly": True}, - "current_value": {"readonly": True}, - "partition_id": {"readonly": True}, - "partition_key_range_id": {"readonly": True}, - } - - _attribute_map = { - "unit": {"key": "unit", "type": "str"}, - "name": {"key": "name", "type": "MetricName"}, - "quota_period": {"key": "quotaPeriod", "type": "str"}, - "limit": {"key": "limit", "type": "int"}, - "current_value": {"key": "currentValue", "type": "int"}, - "partition_id": {"key": "partitionId", "type": "str"}, - "partition_key_range_id": {"key": "partitionKeyRangeId", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.partition_id = None - self.partition_key_range_id = None - - -class PartitionUsagesResult(_serialization.Model): - """The response to a list partition level usage request. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of partition-level usages for the database. A usage is a point in time - metric. - :vartype value: list[~azure.mgmt.cosmosdb.models.PartitionUsage] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[PartitionUsage]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class PercentileMetric(_serialization.Model): - """Percentile Metric data. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar start_time: The start time for the metric (ISO-8601 format). - :vartype start_time: ~datetime.datetime - :ivar end_time: The end time for the metric (ISO-8601 format). - :vartype end_time: ~datetime.datetime - :ivar time_grain: The time grain to be used to summarize the metric values. - :vartype time_grain: str - :ivar unit: The unit of the metric. Known values are: "Count", "Bytes", "Seconds", "Percent", - "CountPerSecond", "BytesPerSecond", and "Milliseconds". - :vartype unit: str or ~azure.mgmt.cosmosdb.models.UnitType - :ivar name: The name information for the metric. - :vartype name: ~azure.mgmt.cosmosdb.models.MetricName - :ivar metric_values: The percentile metric values for the specified time window and timestep. - :vartype metric_values: list[~azure.mgmt.cosmosdb.models.PercentileMetricValue] - """ - - _validation = { - "start_time": {"readonly": True}, - "end_time": {"readonly": True}, - "time_grain": {"readonly": True}, - "unit": {"readonly": True}, - "name": {"readonly": True}, - "metric_values": {"readonly": True}, - } - - _attribute_map = { - "start_time": {"key": "startTime", "type": "iso-8601"}, - "end_time": {"key": "endTime", "type": "iso-8601"}, - "time_grain": {"key": "timeGrain", "type": "str"}, - "unit": {"key": "unit", "type": "str"}, - "name": {"key": "name", "type": "MetricName"}, - "metric_values": {"key": "metricValues", "type": "[PercentileMetricValue]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.start_time = None - self.end_time = None - self.time_grain = None - self.unit = None - self.name = None - self.metric_values = None - - -class PercentileMetricListResult(_serialization.Model): - """The response to a list percentile metrics request. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of percentile metrics for the account. - :vartype value: list[~azure.mgmt.cosmosdb.models.PercentileMetric] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[PercentileMetric]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class PercentileMetricValue(MetricValue): # pylint: disable=too-many-instance-attributes - """Represents percentile metrics values. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar count: The number of values for the metric. - :vartype count: int - :ivar average: The average value of the metric. - :vartype average: float - :ivar maximum: The max value of the metric. - :vartype maximum: float - :ivar minimum: The min value of the metric. - :vartype minimum: float - :ivar timestamp: The metric timestamp (ISO-8601 format). - :vartype timestamp: ~datetime.datetime - :ivar total: The total value of the metric. - :vartype total: float - :ivar p10: The 10th percentile value for the metric. - :vartype p10: float - :ivar p25: The 25th percentile value for the metric. - :vartype p25: float - :ivar p50: The 50th percentile value for the metric. - :vartype p50: float - :ivar p75: The 75th percentile value for the metric. - :vartype p75: float - :ivar p90: The 90th percentile value for the metric. - :vartype p90: float - :ivar p95: The 95th percentile value for the metric. - :vartype p95: float - :ivar p99: The 99th percentile value for the metric. - :vartype p99: float - """ - - _validation = { - "count": {"readonly": True}, - "average": {"readonly": True}, - "maximum": {"readonly": True}, - "minimum": {"readonly": True}, - "timestamp": {"readonly": True}, - "total": {"readonly": True}, - "p10": {"readonly": True}, - "p25": {"readonly": True}, - "p50": {"readonly": True}, - "p75": {"readonly": True}, - "p90": {"readonly": True}, - "p95": {"readonly": True}, - "p99": {"readonly": True}, - } - - _attribute_map = { - "count": {"key": "_count", "type": "int"}, - "average": {"key": "average", "type": "float"}, - "maximum": {"key": "maximum", "type": "float"}, - "minimum": {"key": "minimum", "type": "float"}, - "timestamp": {"key": "timestamp", "type": "iso-8601"}, - "total": {"key": "total", "type": "float"}, - "p10": {"key": "P10", "type": "float"}, - "p25": {"key": "P25", "type": "float"}, - "p50": {"key": "P50", "type": "float"}, - "p75": {"key": "P75", "type": "float"}, - "p90": {"key": "P90", "type": "float"}, - "p95": {"key": "P95", "type": "float"}, - "p99": {"key": "P99", "type": "float"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.p10 = None - self.p25 = None - self.p50 = None - self.p75 = None - self.p90 = None - self.p95 = None - self.p99 = None - - -class PeriodicModeBackupPolicy(BackupPolicy): - """The object representing periodic mode backup policy. - - All required parameters must be populated in order to send to server. - - :ivar type: Describes the mode of backups. Required. Known values are: "Periodic" and - "Continuous". - :vartype type: str or ~azure.mgmt.cosmosdb.models.BackupPolicyType - :ivar migration_state: The object representing the state of the migration between the backup - policies. - :vartype migration_state: ~azure.mgmt.cosmosdb.models.BackupPolicyMigrationState - :ivar periodic_mode_properties: Configuration values for periodic mode backup. - :vartype periodic_mode_properties: ~azure.mgmt.cosmosdb.models.PeriodicModeProperties - """ - - _validation = { - "type": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "migration_state": {"key": "migrationState", "type": "BackupPolicyMigrationState"}, - "periodic_mode_properties": {"key": "periodicModeProperties", "type": "PeriodicModeProperties"}, - } - - def __init__( - self, - *, - migration_state: Optional["_models.BackupPolicyMigrationState"] = None, - periodic_mode_properties: Optional["_models.PeriodicModeProperties"] = None, - **kwargs: Any - ) -> None: - """ - :keyword migration_state: The object representing the state of the migration between the backup - policies. - :paramtype migration_state: ~azure.mgmt.cosmosdb.models.BackupPolicyMigrationState - :keyword periodic_mode_properties: Configuration values for periodic mode backup. - :paramtype periodic_mode_properties: ~azure.mgmt.cosmosdb.models.PeriodicModeProperties - """ - super().__init__(migration_state=migration_state, **kwargs) - self.type: str = "Periodic" - self.periodic_mode_properties = periodic_mode_properties - - -class PeriodicModeProperties(_serialization.Model): - """Configuration values for periodic mode backup. - - :ivar backup_interval_in_minutes: An integer representing the interval in minutes between two - backups. - :vartype backup_interval_in_minutes: int - :ivar backup_retention_interval_in_hours: An integer representing the time (in hours) that each - backup is retained. - :vartype backup_retention_interval_in_hours: int - :ivar backup_storage_redundancy: Enum to indicate type of backup residency. Known values are: - "Geo", "Local", and "Zone". - :vartype backup_storage_redundancy: str or ~azure.mgmt.cosmosdb.models.BackupStorageRedundancy - """ - - _validation = { - "backup_interval_in_minutes": {"minimum": 0}, - "backup_retention_interval_in_hours": {"minimum": 0}, - } - - _attribute_map = { - "backup_interval_in_minutes": {"key": "backupIntervalInMinutes", "type": "int"}, - "backup_retention_interval_in_hours": {"key": "backupRetentionIntervalInHours", "type": "int"}, - "backup_storage_redundancy": {"key": "backupStorageRedundancy", "type": "str"}, - } - - def __init__( - self, - *, - backup_interval_in_minutes: Optional[int] = None, - backup_retention_interval_in_hours: Optional[int] = None, - backup_storage_redundancy: Optional[Union[str, "_models.BackupStorageRedundancy"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword backup_interval_in_minutes: An integer representing the interval in minutes between - two backups. - :paramtype backup_interval_in_minutes: int - :keyword backup_retention_interval_in_hours: An integer representing the time (in hours) that - each backup is retained. - :paramtype backup_retention_interval_in_hours: int - :keyword backup_storage_redundancy: Enum to indicate type of backup residency. Known values - are: "Geo", "Local", and "Zone". - :paramtype backup_storage_redundancy: str or - ~azure.mgmt.cosmosdb.models.BackupStorageRedundancy - """ - super().__init__(**kwargs) - self.backup_interval_in_minutes = backup_interval_in_minutes - self.backup_retention_interval_in_hours = backup_retention_interval_in_hours - self.backup_storage_redundancy = backup_storage_redundancy - - -class Permission(_serialization.Model): - """The set of data plane operations permitted through this Role Definition. - - :ivar data_actions: An array of data actions that are allowed. - :vartype data_actions: list[str] - :ivar not_data_actions: An array of data actions that are denied. - :vartype not_data_actions: list[str] - """ - - _attribute_map = { - "data_actions": {"key": "dataActions", "type": "[str]"}, - "not_data_actions": {"key": "notDataActions", "type": "[str]"}, - } - - def __init__( - self, *, data_actions: Optional[List[str]] = None, not_data_actions: Optional[List[str]] = None, **kwargs: Any - ) -> None: - """ - :keyword data_actions: An array of data actions that are allowed. - :paramtype data_actions: list[str] - :keyword not_data_actions: An array of data actions that are denied. - :paramtype not_data_actions: list[str] - """ - super().__init__(**kwargs) - self.data_actions = data_actions - self.not_data_actions = not_data_actions - - -class PhysicalPartitionId(_serialization.Model): - """PhysicalPartitionId object. - - All required parameters must be populated in order to send to server. - - :ivar id: Id of a physical partition. Required. - :vartype id: str - """ - - _validation = { - "id": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - } - - def __init__(self, *, id: str, **kwargs: Any) -> None: # pylint: disable=redefined-builtin - """ - :keyword id: Id of a physical partition. Required. - :paramtype id: str - """ - super().__init__(**kwargs) - self.id = id - - -class PhysicalPartitionStorageInfo(_serialization.Model): - """The storage of a physical partition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique identifier of the partition. - :vartype id: str - :ivar storage_in_kb: The storage in KB for the physical partition. - :vartype storage_in_kb: float - """ - - _validation = { - "id": {"readonly": True}, - "storage_in_kb": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "storage_in_kb": {"key": "storageInKB", "type": "float"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.id = None - self.storage_in_kb = None - - -class PhysicalPartitionStorageInfoCollection(_serialization.Model): - """List of physical partitions and their properties returned by a merge operation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar physical_partition_storage_info_collection: List of physical partitions and their - properties. - :vartype physical_partition_storage_info_collection: - list[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfo] - """ - - _validation = { - "physical_partition_storage_info_collection": {"readonly": True}, - } - - _attribute_map = { - "physical_partition_storage_info_collection": { - "key": "physicalPartitionStorageInfoCollection", - "type": "[PhysicalPartitionStorageInfo]", - }, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.physical_partition_storage_info_collection = None - - -class PhysicalPartitionThroughputInfoProperties(_serialization.Model): # pylint: disable=name-too-long - """The properties of an Azure Cosmos DB PhysicalPartitionThroughputInfoProperties object. - - :ivar physical_partition_throughput_info: Array of physical partition throughput info objects. - :vartype physical_partition_throughput_info: - list[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResource] - """ - - _attribute_map = { - "physical_partition_throughput_info": { - "key": "physicalPartitionThroughputInfo", - "type": "[PhysicalPartitionThroughputInfoResource]", - }, - } - - def __init__( - self, - *, - physical_partition_throughput_info: Optional[List["_models.PhysicalPartitionThroughputInfoResource"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword physical_partition_throughput_info: Array of physical partition throughput info - objects. - :paramtype physical_partition_throughput_info: - list[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResource] - """ - super().__init__(**kwargs) - self.physical_partition_throughput_info = physical_partition_throughput_info - - -class PhysicalPartitionThroughputInfoResource(_serialization.Model): - """PhysicalPartitionThroughputInfo object. - - All required parameters must be populated in order to send to server. - - :ivar id: Id of a physical partition. Required. - :vartype id: str - :ivar throughput: Throughput of a physical partition. - :vartype throughput: float - """ - - _validation = { - "id": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "throughput": {"key": "throughput", "type": "float"}, - } - - def __init__( - self, *, id: str, throughput: Optional[float] = None, **kwargs: Any # pylint: disable=redefined-builtin - ) -> None: - """ - :keyword id: Id of a physical partition. Required. - :paramtype id: str - :keyword throughput: Throughput of a physical partition. - :paramtype throughput: float - """ - super().__init__(**kwargs) - self.id = id - self.throughput = throughput - - -class PhysicalPartitionThroughputInfoResult(ARMResourceProperties): - """An Azure Cosmos DB PhysicalPartitionThroughputInfoResult object. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: properties of physical partition throughput info. - :vartype resource: - ~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResultPropertiesResource - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "PhysicalPartitionThroughputInfoResultPropertiesResource"}, - } - - def __init__( - self, - *, - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - resource: Optional["_models.PhysicalPartitionThroughputInfoResultPropertiesResource"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: properties of physical partition throughput info. - :paramtype resource: - ~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResultPropertiesResource - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - - -class PhysicalPartitionThroughputInfoResultPropertiesResource( - PhysicalPartitionThroughputInfoProperties -): # pylint: disable=name-too-long - """properties of physical partition throughput info. - - :ivar physical_partition_throughput_info: Array of physical partition throughput info objects. - :vartype physical_partition_throughput_info: - list[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResource] - """ - - -class PrivateEndpointConnection(ProxyResource): - """A private endpoint connection. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Fully qualified resource ID for the resource. E.g. - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or - "Microsoft.Storage/storageAccounts". - :vartype type: str - :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy - information. - :vartype system_data: ~azure.mgmt.cosmosdb.models.SystemData - :ivar private_endpoint: Private endpoint which the connection belongs to. - :vartype private_endpoint: ~azure.mgmt.cosmosdb.models.PrivateEndpointProperty - :ivar private_link_service_connection_state: Connection State of the Private Endpoint - Connection. - :vartype private_link_service_connection_state: - ~azure.mgmt.cosmosdb.models.PrivateLinkServiceConnectionStateProperty - :ivar group_id: Group id of the private endpoint. - :vartype group_id: str - :ivar provisioning_state: Provisioning state of the private endpoint. - :vartype provisioning_state: str - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "system_data": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "system_data": {"key": "systemData", "type": "SystemData"}, - "private_endpoint": {"key": "properties.privateEndpoint", "type": "PrivateEndpointProperty"}, - "private_link_service_connection_state": { - "key": "properties.privateLinkServiceConnectionState", - "type": "PrivateLinkServiceConnectionStateProperty", - }, - "group_id": {"key": "properties.groupId", "type": "str"}, - "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, - } - - def __init__( - self, - *, - private_endpoint: Optional["_models.PrivateEndpointProperty"] = None, - private_link_service_connection_state: Optional["_models.PrivateLinkServiceConnectionStateProperty"] = None, - group_id: Optional[str] = None, - provisioning_state: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword private_endpoint: Private endpoint which the connection belongs to. - :paramtype private_endpoint: ~azure.mgmt.cosmosdb.models.PrivateEndpointProperty - :keyword private_link_service_connection_state: Connection State of the Private Endpoint - Connection. - :paramtype private_link_service_connection_state: - ~azure.mgmt.cosmosdb.models.PrivateLinkServiceConnectionStateProperty - :keyword group_id: Group id of the private endpoint. - :paramtype group_id: str - :keyword provisioning_state: Provisioning state of the private endpoint. - :paramtype provisioning_state: str - """ - super().__init__(**kwargs) - self.private_endpoint = private_endpoint - self.private_link_service_connection_state = private_link_service_connection_state - self.group_id = group_id - self.provisioning_state = provisioning_state - - -class PrivateEndpointConnectionListResult(_serialization.Model): - """A list of private endpoint connections. - - :ivar value: Array of private endpoint connections. - :vartype value: list[~azure.mgmt.cosmosdb.models.PrivateEndpointConnection] - """ - - _attribute_map = { - "value": {"key": "value", "type": "[PrivateEndpointConnection]"}, - } - - def __init__(self, *, value: Optional[List["_models.PrivateEndpointConnection"]] = None, **kwargs: Any) -> None: - """ - :keyword value: Array of private endpoint connections. - :paramtype value: list[~azure.mgmt.cosmosdb.models.PrivateEndpointConnection] - """ - super().__init__(**kwargs) - self.value = value - - -class PrivateEndpointProperty(_serialization.Model): - """Private endpoint which the connection belongs to. - - :ivar id: Resource id of the private endpoint. - :vartype id: str - """ - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - } - - def __init__(self, *, id: Optional[str] = None, **kwargs: Any) -> None: # pylint: disable=redefined-builtin - """ - :keyword id: Resource id of the private endpoint. - :paramtype id: str - """ - super().__init__(**kwargs) - self.id = id - - -class PrivateLinkResource(ARMProxyResource): - """A private link resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the database account. - :vartype id: str - :ivar name: The name of the database account. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar group_id: The private link resource group id. - :vartype group_id: str - :ivar required_members: The private link resource required member names. - :vartype required_members: list[str] - :ivar required_zone_names: The private link resource required zone names. - :vartype required_zone_names: list[str] - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "group_id": {"readonly": True}, - "required_members": {"readonly": True}, - "required_zone_names": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "group_id": {"key": "properties.groupId", "type": "str"}, - "required_members": {"key": "properties.requiredMembers", "type": "[str]"}, - "required_zone_names": {"key": "properties.requiredZoneNames", "type": "[str]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.group_id = None - self.required_members = None - self.required_zone_names = None - - -class PrivateLinkResourceListResult(_serialization.Model): - """A list of private link resources. - - :ivar value: Array of private link resources. - :vartype value: list[~azure.mgmt.cosmosdb.models.PrivateLinkResource] - """ - - _attribute_map = { - "value": {"key": "value", "type": "[PrivateLinkResource]"}, - } - - def __init__(self, *, value: Optional[List["_models.PrivateLinkResource"]] = None, **kwargs: Any) -> None: - """ - :keyword value: Array of private link resources. - :paramtype value: list[~azure.mgmt.cosmosdb.models.PrivateLinkResource] - """ - super().__init__(**kwargs) - self.value = value - - -class PrivateLinkServiceConnectionStateProperty(_serialization.Model): # pylint: disable=name-too-long - """Connection State of the Private Endpoint Connection. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar status: The private link service connection status. - :vartype status: str - :ivar description: The private link service connection description. - :vartype description: str - :ivar actions_required: Any action that is required beyond basic workflow (approve/ reject/ - disconnect). - :vartype actions_required: str - """ - - _validation = { - "actions_required": {"readonly": True}, - } - - _attribute_map = { - "status": {"key": "status", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "actions_required": {"key": "actionsRequired", "type": "str"}, - } - - def __init__(self, *, status: Optional[str] = None, description: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword status: The private link service connection status. - :paramtype status: str - :keyword description: The private link service connection description. - :paramtype description: str - """ - super().__init__(**kwargs) - self.status = status - self.description = description - self.actions_required = None - - -class Privilege(_serialization.Model): - """The set of data plane operations permitted through this Role Definition. - - :ivar resource: An Azure Cosmos DB Mongo DB Resource. - :vartype resource: ~azure.mgmt.cosmosdb.models.PrivilegeResource - :ivar actions: An array of actions that are allowed. - :vartype actions: list[str] - """ - - _attribute_map = { - "resource": {"key": "resource", "type": "PrivilegeResource"}, - "actions": {"key": "actions", "type": "[str]"}, - } - - def __init__( - self, - *, - resource: Optional["_models.PrivilegeResource"] = None, - actions: Optional[List[str]] = None, - **kwargs: Any - ) -> None: - """ - :keyword resource: An Azure Cosmos DB Mongo DB Resource. - :paramtype resource: ~azure.mgmt.cosmosdb.models.PrivilegeResource - :keyword actions: An array of actions that are allowed. - :paramtype actions: list[str] - """ - super().__init__(**kwargs) - self.resource = resource - self.actions = actions - - -class PrivilegeResource(_serialization.Model): - """An Azure Cosmos DB Mongo DB Resource. - - :ivar db: The database name the role is applied. - :vartype db: str - :ivar collection: The collection name the role is applied. - :vartype collection: str - """ - - _attribute_map = { - "db": {"key": "db", "type": "str"}, - "collection": {"key": "collection", "type": "str"}, - } - - def __init__(self, *, db: Optional[str] = None, collection: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword db: The database name the role is applied. - :paramtype db: str - :keyword collection: The collection name the role is applied. - :paramtype collection: str - """ - super().__init__(**kwargs) - self.db = db - self.collection = collection - - -class ProvisioningIssue(_serialization.Model): - """Describes a provisioning issue for a network security perimeter configuration. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar name: Name of the issue. - :vartype name: str - :ivar properties: Details of a provisioning issue for a network security perimeter (NSP) - configuration. Resource providers should generate separate provisioning issue elements for each - separate issue detected, and include a meaningful and distinctive description, as well as any - appropriate suggestedResourceIds and suggestedAccessRules. - :vartype properties: ~azure.mgmt.cosmosdb.models.ProvisioningIssueProperties - """ - - _validation = { - "name": {"readonly": True}, - "properties": {"readonly": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "properties": {"key": "properties", "type": "ProvisioningIssueProperties"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.name = None - self.properties = None - - -class ProvisioningIssueProperties(_serialization.Model): - """Details of a provisioning issue for a network security perimeter (NSP) configuration. Resource - providers should generate separate provisioning issue elements for each separate issue - detected, and include a meaningful and distinctive description, as well as any appropriate - suggestedResourceIds and suggestedAccessRules. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar issue_type: Type of issue. Known values are: "Unknown", - "ConfigurationPropagationFailure", "MissingPerimeterConfiguration", and - "MissingIdentityConfiguration". - :vartype issue_type: str or ~azure.mgmt.cosmosdb.models.IssueType - :ivar severity: Severity of the issue. Known values are: "Warning" and "Error". - :vartype severity: str or ~azure.mgmt.cosmosdb.models.Severity - :ivar description: Description of the issue. - :vartype description: str - :ivar suggested_resource_ids: Fully qualified resource IDs of suggested resources that can be - associated to the network security perimeter (NSP) to remediate the issue. - :vartype suggested_resource_ids: list[str] - :ivar suggested_access_rules: Access rules that can be added to the network security profile - (NSP) to remediate the issue. - :vartype suggested_access_rules: list[~azure.mgmt.cosmosdb.models.AccessRule] - """ - - _validation = { - "issue_type": {"readonly": True}, - "severity": {"readonly": True}, - "description": {"readonly": True}, - "suggested_resource_ids": {"readonly": True}, - "suggested_access_rules": {"readonly": True}, - } - - _attribute_map = { - "issue_type": {"key": "issueType", "type": "str"}, - "severity": {"key": "severity", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "suggested_resource_ids": {"key": "suggestedResourceIds", "type": "[str]"}, - "suggested_access_rules": {"key": "suggestedAccessRules", "type": "[AccessRule]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.issue_type = None - self.severity = None - self.description = None - self.suggested_resource_ids = None - self.suggested_access_rules = None - - -class RedistributeThroughputParameters(ARMResourceProperties): - """Cosmos DB redistribute throughput parameters object. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: The standard JSON format of a resource throughput. Required. - :vartype resource: ~azure.mgmt.cosmosdb.models.RedistributeThroughputPropertiesResource - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "resource": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "RedistributeThroughputPropertiesResource"}, - } - - def __init__( - self, - *, - resource: "_models.RedistributeThroughputPropertiesResource", - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: The standard JSON format of a resource throughput. Required. - :paramtype resource: ~azure.mgmt.cosmosdb.models.RedistributeThroughputPropertiesResource - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - - -class RedistributeThroughputPropertiesResource(_serialization.Model): - """Resource to redistribute throughput for Azure Cosmos DB resource. - - All required parameters must be populated in order to send to server. - - :ivar throughput_policy: ThroughputPolicy to apply for throughput redistribution. Required. - Known values are: "none", "equal", and "custom". - :vartype throughput_policy: str or ~azure.mgmt.cosmosdb.models.ThroughputPolicyType - :ivar target_physical_partition_throughput_info: Array of - PhysicalPartitionThroughputInfoResource objects. Required. - :vartype target_physical_partition_throughput_info: - list[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResource] - :ivar source_physical_partition_throughput_info: Array of - PhysicalPartitionThroughputInfoResource objects. Required. - :vartype source_physical_partition_throughput_info: - list[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResource] - """ - - _validation = { - "throughput_policy": {"required": True}, - "target_physical_partition_throughput_info": {"required": True}, - "source_physical_partition_throughput_info": {"required": True}, - } - - _attribute_map = { - "throughput_policy": {"key": "throughputPolicy", "type": "str"}, - "target_physical_partition_throughput_info": { - "key": "targetPhysicalPartitionThroughputInfo", - "type": "[PhysicalPartitionThroughputInfoResource]", - }, - "source_physical_partition_throughput_info": { - "key": "sourcePhysicalPartitionThroughputInfo", - "type": "[PhysicalPartitionThroughputInfoResource]", - }, - } - - def __init__( - self, - *, - throughput_policy: Union[str, "_models.ThroughputPolicyType"], - target_physical_partition_throughput_info: List["_models.PhysicalPartitionThroughputInfoResource"], - source_physical_partition_throughput_info: List["_models.PhysicalPartitionThroughputInfoResource"], - **kwargs: Any - ) -> None: - """ - :keyword throughput_policy: ThroughputPolicy to apply for throughput redistribution. Required. - Known values are: "none", "equal", and "custom". - :paramtype throughput_policy: str or ~azure.mgmt.cosmosdb.models.ThroughputPolicyType - :keyword target_physical_partition_throughput_info: Array of - PhysicalPartitionThroughputInfoResource objects. Required. - :paramtype target_physical_partition_throughput_info: - list[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResource] - :keyword source_physical_partition_throughput_info: Array of - PhysicalPartitionThroughputInfoResource objects. Required. - :paramtype source_physical_partition_throughput_info: - list[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResource] - """ - super().__init__(**kwargs) - self.throughput_policy = throughput_policy - self.target_physical_partition_throughput_info = target_physical_partition_throughput_info - self.source_physical_partition_throughput_info = source_physical_partition_throughput_info - - -class RegionForOnlineOffline(_serialization.Model): - """Cosmos DB region to online or offline. - - All required parameters must be populated in order to send to server. - - :ivar region: Cosmos DB region, with spaces between words and each word capitalized. Required. - :vartype region: str - """ - - _validation = { - "region": {"required": True}, - } - - _attribute_map = { - "region": {"key": "region", "type": "str"}, - } - - def __init__(self, *, region: str, **kwargs: Any) -> None: - """ - :keyword region: Cosmos DB region, with spaces between words and each word capitalized. - Required. - :paramtype region: str - """ - super().__init__(**kwargs) - self.region = region - - -class ResourceAssociation(_serialization.Model): - """Information about resource association. - - :ivar name: Name of the resource association. - :vartype name: str - :ivar access_mode: Access mode of the resource association. Known values are: "Enforced", - "Learning", and "Audit". - :vartype access_mode: str or ~azure.mgmt.cosmosdb.models.ResourceAssociationAccessMode - """ - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "access_mode": {"key": "accessMode", "type": "str"}, - } - - def __init__( - self, - *, - name: Optional[str] = None, - access_mode: Optional[Union[str, "_models.ResourceAssociationAccessMode"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: Name of the resource association. - :paramtype name: str - :keyword access_mode: Access mode of the resource association. Known values are: "Enforced", - "Learning", and "Audit". - :paramtype access_mode: str or ~azure.mgmt.cosmosdb.models.ResourceAssociationAccessMode - """ - super().__init__(**kwargs) - self.name = name - self.access_mode = access_mode - - -class RestoreParametersBase(_serialization.Model): - """Parameters to indicate the information about the restore. - - :ivar restore_source: The id of the restorable database account from which the restore has to - be initiated. For example: - /subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{restorableDatabaseAccountName}. # pylint: disable=line-too-long - :vartype restore_source: str - :ivar restore_timestamp_in_utc: Time to which the account has to be restored (ISO-8601 format). - :vartype restore_timestamp_in_utc: ~datetime.datetime - :ivar restore_with_ttl_disabled: Specifies whether the restored account will have Time-To-Live - disabled upon the successful restore. - :vartype restore_with_ttl_disabled: bool - """ - - _attribute_map = { - "restore_source": {"key": "restoreSource", "type": "str"}, - "restore_timestamp_in_utc": {"key": "restoreTimestampInUtc", "type": "iso-8601"}, - "restore_with_ttl_disabled": {"key": "restoreWithTtlDisabled", "type": "bool"}, - } - - def __init__( - self, - *, - restore_source: Optional[str] = None, - restore_timestamp_in_utc: Optional[datetime.datetime] = None, - restore_with_ttl_disabled: Optional[bool] = None, - **kwargs: Any - ) -> None: - """ - :keyword restore_source: The id of the restorable database account from which the restore has - to be initiated. For example: - /subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{restorableDatabaseAccountName}. # pylint: disable=line-too-long - :paramtype restore_source: str - :keyword restore_timestamp_in_utc: Time to which the account has to be restored (ISO-8601 - format). - :paramtype restore_timestamp_in_utc: ~datetime.datetime - :keyword restore_with_ttl_disabled: Specifies whether the restored account will have - Time-To-Live disabled upon the successful restore. - :paramtype restore_with_ttl_disabled: bool - """ - super().__init__(**kwargs) - self.restore_source = restore_source - self.restore_timestamp_in_utc = restore_timestamp_in_utc - self.restore_with_ttl_disabled = restore_with_ttl_disabled - - -class ResourceRestoreParameters(RestoreParametersBase): - """Parameters to indicate the information about the restore. - - :ivar restore_source: The id of the restorable database account from which the restore has to - be initiated. For example: - /subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{restorableDatabaseAccountName}. # pylint: disable=line-too-long - :vartype restore_source: str - :ivar restore_timestamp_in_utc: Time to which the account has to be restored (ISO-8601 format). - :vartype restore_timestamp_in_utc: ~datetime.datetime - :ivar restore_with_ttl_disabled: Specifies whether the restored account will have Time-To-Live - disabled upon the successful restore. - :vartype restore_with_ttl_disabled: bool - """ - - -class RestorableDatabaseAccountGetResult(_serialization.Model): - """A Azure Cosmos DB restorable database account. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar account_name: The name of the global database account. - :vartype account_name: str - :ivar creation_time: The creation time of the restorable database account (ISO-8601 format). - :vartype creation_time: ~datetime.datetime - :ivar oldest_restorable_time: The least recent time at which the database account can be - restored to (ISO-8601 format). - :vartype oldest_restorable_time: ~datetime.datetime - :ivar deletion_time: The time at which the restorable database account has been deleted - (ISO-8601 format). - :vartype deletion_time: ~datetime.datetime - :ivar api_type: The API type of the restorable database account. Known values are: "MongoDB", - "Gremlin", "Cassandra", "Table", "Sql", and "GremlinV2". - :vartype api_type: str or ~azure.mgmt.cosmosdb.models.ApiType - :ivar restorable_locations: List of regions where the of the database account can be restored - from. - :vartype restorable_locations: list[~azure.mgmt.cosmosdb.models.RestorableLocationResource] - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "api_type": {"readonly": True}, - "restorable_locations": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "account_name": {"key": "properties.accountName", "type": "str"}, - "creation_time": {"key": "properties.creationTime", "type": "iso-8601"}, - "oldest_restorable_time": {"key": "properties.oldestRestorableTime", "type": "iso-8601"}, - "deletion_time": {"key": "properties.deletionTime", "type": "iso-8601"}, - "api_type": {"key": "properties.apiType", "type": "str"}, - "restorable_locations": {"key": "properties.restorableLocations", "type": "[RestorableLocationResource]"}, - } - - def __init__( - self, - *, - location: Optional[str] = None, - account_name: Optional[str] = None, - creation_time: Optional[datetime.datetime] = None, - oldest_restorable_time: Optional[datetime.datetime] = None, - deletion_time: Optional[datetime.datetime] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword account_name: The name of the global database account. - :paramtype account_name: str - :keyword creation_time: The creation time of the restorable database account (ISO-8601 format). - :paramtype creation_time: ~datetime.datetime - :keyword oldest_restorable_time: The least recent time at which the database account can be - restored to (ISO-8601 format). - :paramtype oldest_restorable_time: ~datetime.datetime - :keyword deletion_time: The time at which the restorable database account has been deleted - (ISO-8601 format). - :paramtype deletion_time: ~datetime.datetime - """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.location = location - self.account_name = account_name - self.creation_time = creation_time - self.oldest_restorable_time = oldest_restorable_time - self.deletion_time = deletion_time - self.api_type = None - self.restorable_locations = None - - -class RestorableDatabaseAccountsListResult(_serialization.Model): - """The List operation response, that contains the restorable database accounts and their - properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of restorable database accounts and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.RestorableDatabaseAccountGetResult] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[RestorableDatabaseAccountGetResult]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class RestorableGremlinDatabaseGetResult(_serialization.Model): - """An Azure Cosmos DB Gremlin database event. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource Identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar resource: The resource of an Azure Cosmos DB Gremlin database event. - :vartype resource: ~azure.mgmt.cosmosdb.models.RestorableGremlinDatabasePropertiesResource - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "resource": {"key": "properties.resource", "type": "RestorableGremlinDatabasePropertiesResource"}, - } - - def __init__( - self, *, resource: Optional["_models.RestorableGremlinDatabasePropertiesResource"] = None, **kwargs: Any - ) -> None: - """ - :keyword resource: The resource of an Azure Cosmos DB Gremlin database event. - :paramtype resource: ~azure.mgmt.cosmosdb.models.RestorableGremlinDatabasePropertiesResource - """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.resource = resource - - -class RestorableGremlinDatabasePropertiesResource(_serialization.Model): # pylint: disable=name-too-long - """The resource of an Azure Cosmos DB Gremlin database event. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar rid: A system generated property. A unique identifier. - :vartype rid: str - :ivar operation_type: The operation type of this database event. Known values are: "Create", - "Replace", "Delete", "Recreate", and "SystemOperation". - :vartype operation_type: str or ~azure.mgmt.cosmosdb.models.OperationType - :ivar can_undelete: A state of this database to identify if this database is restorable in same - account. - :vartype can_undelete: str - :ivar can_undelete_reason: The reason why this database can not be restored in same account. - :vartype can_undelete_reason: str - :ivar event_timestamp: The time when this database event happened. - :vartype event_timestamp: str - :ivar owner_id: The name of this Gremlin database. - :vartype owner_id: str - :ivar owner_resource_id: The resource ID of this Gremlin database. - :vartype owner_resource_id: str - """ - - _validation = { - "rid": {"readonly": True}, - "operation_type": {"readonly": True}, - "can_undelete": {"readonly": True}, - "can_undelete_reason": {"readonly": True}, - "event_timestamp": {"readonly": True}, - "owner_id": {"readonly": True}, - "owner_resource_id": {"readonly": True}, - } - - _attribute_map = { - "rid": {"key": "_rid", "type": "str"}, - "operation_type": {"key": "operationType", "type": "str"}, - "can_undelete": {"key": "canUndelete", "type": "str"}, - "can_undelete_reason": {"key": "canUndeleteReason", "type": "str"}, - "event_timestamp": {"key": "eventTimestamp", "type": "str"}, - "owner_id": {"key": "ownerId", "type": "str"}, - "owner_resource_id": {"key": "ownerResourceId", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.rid = None - self.operation_type = None - self.can_undelete = None - self.can_undelete_reason = None - self.event_timestamp = None - self.owner_id = None - self.owner_resource_id = None - - -class RestorableGremlinDatabasesListResult(_serialization.Model): - """The List operation response, that contains the Gremlin database events and their properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of Gremlin database events and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.RestorableGremlinDatabaseGetResult] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[RestorableGremlinDatabaseGetResult]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class RestorableGremlinGraphGetResult(_serialization.Model): - """An Azure Cosmos DB Gremlin graph event. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource Identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar resource: The resource of an Azure Cosmos DB Gremlin graph event. - :vartype resource: ~azure.mgmt.cosmosdb.models.RestorableGremlinGraphPropertiesResource - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "resource": {"key": "properties.resource", "type": "RestorableGremlinGraphPropertiesResource"}, - } - - def __init__( - self, *, resource: Optional["_models.RestorableGremlinGraphPropertiesResource"] = None, **kwargs: Any - ) -> None: - """ - :keyword resource: The resource of an Azure Cosmos DB Gremlin graph event. - :paramtype resource: ~azure.mgmt.cosmosdb.models.RestorableGremlinGraphPropertiesResource - """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.resource = resource - - -class RestorableGremlinGraphPropertiesResource(_serialization.Model): - """The resource of an Azure Cosmos DB Gremlin graph event. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar rid: A system generated property. A unique identifier. - :vartype rid: str - :ivar operation_type: The operation type of this graph event. Known values are: "Create", - "Replace", "Delete", "Recreate", and "SystemOperation". - :vartype operation_type: str or ~azure.mgmt.cosmosdb.models.OperationType - :ivar can_undelete: A state of this graph to identify if this graph is restorable in same - account. - :vartype can_undelete: str - :ivar can_undelete_reason: The reason why this graph can not be restored in same account. - :vartype can_undelete_reason: str - :ivar event_timestamp: The time when this graph event happened. - :vartype event_timestamp: str - :ivar owner_id: The name of this Gremlin graph. - :vartype owner_id: str - :ivar owner_resource_id: The resource ID of this Gremlin graph. - :vartype owner_resource_id: str - """ - - _validation = { - "rid": {"readonly": True}, - "operation_type": {"readonly": True}, - "can_undelete": {"readonly": True}, - "can_undelete_reason": {"readonly": True}, - "event_timestamp": {"readonly": True}, - "owner_id": {"readonly": True}, - "owner_resource_id": {"readonly": True}, - } - - _attribute_map = { - "rid": {"key": "_rid", "type": "str"}, - "operation_type": {"key": "operationType", "type": "str"}, - "can_undelete": {"key": "canUndelete", "type": "str"}, - "can_undelete_reason": {"key": "canUndeleteReason", "type": "str"}, - "event_timestamp": {"key": "eventTimestamp", "type": "str"}, - "owner_id": {"key": "ownerId", "type": "str"}, - "owner_resource_id": {"key": "ownerResourceId", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.rid = None - self.operation_type = None - self.can_undelete = None - self.can_undelete_reason = None - self.event_timestamp = None - self.owner_id = None - self.owner_resource_id = None - - -class RestorableGremlinGraphsListResult(_serialization.Model): - """The List operation response, that contains the Gremlin graph events and their properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of Gremlin graph events and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.RestorableGremlinGraphGetResult] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[RestorableGremlinGraphGetResult]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class RestorableGremlinResourcesGetResult(_serialization.Model): - """Specific Databases to restore. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar database_name: The name of the gremlin database available for restore. - :vartype database_name: str - :ivar graph_names: The names of the graphs available for restore. - :vartype graph_names: list[str] - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "database_name": {"key": "databaseName", "type": "str"}, - "graph_names": {"key": "graphNames", "type": "[str]"}, - } - - def __init__( - self, *, database_name: Optional[str] = None, graph_names: Optional[List[str]] = None, **kwargs: Any - ) -> None: - """ - :keyword database_name: The name of the gremlin database available for restore. - :paramtype database_name: str - :keyword graph_names: The names of the graphs available for restore. - :paramtype graph_names: list[str] - """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.database_name = database_name - self.graph_names = graph_names - - -class RestorableGremlinResourcesListResult(_serialization.Model): - """The List operation response, that contains the restorable Gremlin resources. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of restorable Gremlin resources, including the gremlin database and graph - names. - :vartype value: list[~azure.mgmt.cosmosdb.models.RestorableGremlinResourcesGetResult] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[RestorableGremlinResourcesGetResult]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class RestorableLocationResource(_serialization.Model): - """Properties of the regional restorable account. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar location_name: The location of the regional restorable account. - :vartype location_name: str - :ivar regional_database_account_instance_id: The instance id of the regional restorable - account. - :vartype regional_database_account_instance_id: str - :ivar creation_time: The creation time of the regional restorable database account (ISO-8601 - format). - :vartype creation_time: ~datetime.datetime - :ivar deletion_time: The time at which the regional restorable database account has been - deleted (ISO-8601 format). - :vartype deletion_time: ~datetime.datetime - """ - - _validation = { - "location_name": {"readonly": True}, - "regional_database_account_instance_id": {"readonly": True}, - "creation_time": {"readonly": True}, - "deletion_time": {"readonly": True}, - } - - _attribute_map = { - "location_name": {"key": "locationName", "type": "str"}, - "regional_database_account_instance_id": {"key": "regionalDatabaseAccountInstanceId", "type": "str"}, - "creation_time": {"key": "creationTime", "type": "iso-8601"}, - "deletion_time": {"key": "deletionTime", "type": "iso-8601"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.location_name = None - self.regional_database_account_instance_id = None - self.creation_time = None - self.deletion_time = None - - -class RestorableMongodbCollectionGetResult(_serialization.Model): - """An Azure Cosmos DB MongoDB collection event. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource Identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar resource: The resource of an Azure Cosmos DB MongoDB collection event. - :vartype resource: ~azure.mgmt.cosmosdb.models.RestorableMongodbCollectionPropertiesResource - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "resource": {"key": "properties.resource", "type": "RestorableMongodbCollectionPropertiesResource"}, - } - - def __init__( - self, *, resource: Optional["_models.RestorableMongodbCollectionPropertiesResource"] = None, **kwargs: Any - ) -> None: - """ - :keyword resource: The resource of an Azure Cosmos DB MongoDB collection event. - :paramtype resource: ~azure.mgmt.cosmosdb.models.RestorableMongodbCollectionPropertiesResource - """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.resource = resource - - -class RestorableMongodbCollectionPropertiesResource(_serialization.Model): # pylint: disable=name-too-long - """The resource of an Azure Cosmos DB MongoDB collection event. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar rid: A system generated property. A unique identifier. - :vartype rid: str - :ivar operation_type: The operation type of this collection event. Known values are: "Create", - "Replace", "Delete", "Recreate", and "SystemOperation". - :vartype operation_type: str or ~azure.mgmt.cosmosdb.models.OperationType - :ivar can_undelete: A state of this collection to identify if this container is restorable in - same account. - :vartype can_undelete: str - :ivar can_undelete_reason: The reason why this collection can not be restored in same account. - :vartype can_undelete_reason: str - :ivar event_timestamp: The time when this collection event happened. - :vartype event_timestamp: str - :ivar owner_id: The name of this MongoDB collection. - :vartype owner_id: str - :ivar owner_resource_id: The resource ID of this MongoDB collection. - :vartype owner_resource_id: str - """ - - _validation = { - "rid": {"readonly": True}, - "operation_type": {"readonly": True}, - "can_undelete": {"readonly": True}, - "can_undelete_reason": {"readonly": True}, - "event_timestamp": {"readonly": True}, - "owner_id": {"readonly": True}, - "owner_resource_id": {"readonly": True}, - } - - _attribute_map = { - "rid": {"key": "_rid", "type": "str"}, - "operation_type": {"key": "operationType", "type": "str"}, - "can_undelete": {"key": "canUndelete", "type": "str"}, - "can_undelete_reason": {"key": "canUndeleteReason", "type": "str"}, - "event_timestamp": {"key": "eventTimestamp", "type": "str"}, - "owner_id": {"key": "ownerId", "type": "str"}, - "owner_resource_id": {"key": "ownerResourceId", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.rid = None - self.operation_type = None - self.can_undelete = None - self.can_undelete_reason = None - self.event_timestamp = None - self.owner_id = None - self.owner_resource_id = None - - -class RestorableMongodbCollectionsListResult(_serialization.Model): - """The List operation response, that contains the MongoDB collection events and their properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of MongoDB collection events and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.RestorableMongodbCollectionGetResult] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[RestorableMongodbCollectionGetResult]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class RestorableMongodbDatabaseGetResult(_serialization.Model): - """An Azure Cosmos DB MongoDB database event. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource Identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar resource: The resource of an Azure Cosmos DB MongoDB database event. - :vartype resource: ~azure.mgmt.cosmosdb.models.RestorableMongodbDatabasePropertiesResource - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "resource": {"key": "properties.resource", "type": "RestorableMongodbDatabasePropertiesResource"}, - } - - def __init__( - self, *, resource: Optional["_models.RestorableMongodbDatabasePropertiesResource"] = None, **kwargs: Any - ) -> None: - """ - :keyword resource: The resource of an Azure Cosmos DB MongoDB database event. - :paramtype resource: ~azure.mgmt.cosmosdb.models.RestorableMongodbDatabasePropertiesResource - """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.resource = resource - - -class RestorableMongodbDatabasePropertiesResource(_serialization.Model): # pylint: disable=name-too-long - """The resource of an Azure Cosmos DB MongoDB database event. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar rid: A system generated property. A unique identifier. - :vartype rid: str - :ivar operation_type: The operation type of this database event. Known values are: "Create", - "Replace", "Delete", "Recreate", and "SystemOperation". - :vartype operation_type: str or ~azure.mgmt.cosmosdb.models.OperationType - :ivar can_undelete: A state of this database to identify if this database is restorable in same - account. - :vartype can_undelete: str - :ivar can_undelete_reason: The reason why this database can not be restored in same account. - :vartype can_undelete_reason: str - :ivar event_timestamp: The time when this database event happened. - :vartype event_timestamp: str - :ivar owner_id: The name of this MongoDB database. - :vartype owner_id: str - :ivar owner_resource_id: The resource ID of this MongoDB database. - :vartype owner_resource_id: str - """ - - _validation = { - "rid": {"readonly": True}, - "operation_type": {"readonly": True}, - "can_undelete": {"readonly": True}, - "can_undelete_reason": {"readonly": True}, - "event_timestamp": {"readonly": True}, - "owner_id": {"readonly": True}, - "owner_resource_id": {"readonly": True}, - } - - _attribute_map = { - "rid": {"key": "_rid", "type": "str"}, - "operation_type": {"key": "operationType", "type": "str"}, - "can_undelete": {"key": "canUndelete", "type": "str"}, - "can_undelete_reason": {"key": "canUndeleteReason", "type": "str"}, - "event_timestamp": {"key": "eventTimestamp", "type": "str"}, - "owner_id": {"key": "ownerId", "type": "str"}, - "owner_resource_id": {"key": "ownerResourceId", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.rid = None - self.operation_type = None - self.can_undelete = None - self.can_undelete_reason = None - self.event_timestamp = None - self.owner_id = None - self.owner_resource_id = None - - -class RestorableMongodbDatabasesListResult(_serialization.Model): - """The List operation response, that contains the MongoDB database events and their properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of MongoDB database events and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.RestorableMongodbDatabaseGetResult] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[RestorableMongodbDatabaseGetResult]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class RestorableMongodbResourcesGetResult(_serialization.Model): - """Specific Databases to restore. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar database_name: The name of the database available for restore. - :vartype database_name: str - :ivar collection_names: The names of the collections available for restore. - :vartype collection_names: list[str] - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "database_name": {"key": "databaseName", "type": "str"}, - "collection_names": {"key": "collectionNames", "type": "[str]"}, - } - - def __init__( - self, *, database_name: Optional[str] = None, collection_names: Optional[List[str]] = None, **kwargs: Any - ) -> None: - """ - :keyword database_name: The name of the database available for restore. - :paramtype database_name: str - :keyword collection_names: The names of the collections available for restore. - :paramtype collection_names: list[str] - """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.database_name = database_name - self.collection_names = collection_names - - -class RestorableMongodbResourcesListResult(_serialization.Model): - """The List operation response, that contains the restorable MongoDB resources. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of restorable MongoDB resources, including the database and collection names. - :vartype value: list[~azure.mgmt.cosmosdb.models.RestorableMongodbResourcesGetResult] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[RestorableMongodbResourcesGetResult]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class RestorableSqlContainerGetResult(_serialization.Model): - """An Azure Cosmos DB SQL container event. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource Identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar resource: The resource of an Azure Cosmos DB SQL container event. - :vartype resource: ~azure.mgmt.cosmosdb.models.RestorableSqlContainerPropertiesResource - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "resource": {"key": "properties.resource", "type": "RestorableSqlContainerPropertiesResource"}, - } - - def __init__( - self, *, resource: Optional["_models.RestorableSqlContainerPropertiesResource"] = None, **kwargs: Any - ) -> None: - """ - :keyword resource: The resource of an Azure Cosmos DB SQL container event. - :paramtype resource: ~azure.mgmt.cosmosdb.models.RestorableSqlContainerPropertiesResource - """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.resource = resource - - -class RestorableSqlContainerPropertiesResource(_serialization.Model): - """The resource of an Azure Cosmos DB SQL container event. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar rid: A system generated property. A unique identifier. - :vartype rid: str - :ivar operation_type: The operation type of this container event. Known values are: "Create", - "Replace", "Delete", "Recreate", and "SystemOperation". - :vartype operation_type: str or ~azure.mgmt.cosmosdb.models.OperationType - :ivar can_undelete: A state of this container to identify if this container is restorable in - same account. - :vartype can_undelete: str - :ivar can_undelete_reason: The reason why this container can not be restored in same account. - :vartype can_undelete_reason: str - :ivar event_timestamp: The when this container event happened. - :vartype event_timestamp: str - :ivar owner_id: The name of this SQL container. - :vartype owner_id: str - :ivar owner_resource_id: The resource ID of this SQL container. - :vartype owner_resource_id: str - :ivar container: Cosmos DB SQL container resource object. - :vartype container: - ~azure.mgmt.cosmosdb.models.RestorableSqlContainerPropertiesResourceContainer - """ - - _validation = { - "rid": {"readonly": True}, - "operation_type": {"readonly": True}, - "can_undelete": {"readonly": True}, - "can_undelete_reason": {"readonly": True}, - "event_timestamp": {"readonly": True}, - "owner_id": {"readonly": True}, - "owner_resource_id": {"readonly": True}, - } - - _attribute_map = { - "rid": {"key": "_rid", "type": "str"}, - "operation_type": {"key": "operationType", "type": "str"}, - "can_undelete": {"key": "canUndelete", "type": "str"}, - "can_undelete_reason": {"key": "canUndeleteReason", "type": "str"}, - "event_timestamp": {"key": "eventTimestamp", "type": "str"}, - "owner_id": {"key": "ownerId", "type": "str"}, - "owner_resource_id": {"key": "ownerResourceId", "type": "str"}, - "container": {"key": "container", "type": "RestorableSqlContainerPropertiesResourceContainer"}, - } - - def __init__( - self, *, container: Optional["_models.RestorableSqlContainerPropertiesResourceContainer"] = None, **kwargs: Any - ) -> None: - """ - :keyword container: Cosmos DB SQL container resource object. - :paramtype container: - ~azure.mgmt.cosmosdb.models.RestorableSqlContainerPropertiesResourceContainer - """ - super().__init__(**kwargs) - self.rid = None - self.operation_type = None - self.can_undelete = None - self.can_undelete_reason = None - self.event_timestamp = None - self.owner_id = None - self.owner_resource_id = None - self.container = container - - -class SqlContainerResource(_serialization.Model): # pylint: disable=too-many-instance-attributes - """Cosmos DB SQL container resource object. - - All required parameters must be populated in order to send to server. - - :ivar id: Name of the Cosmos DB SQL container. Required. - :vartype id: str - :ivar indexing_policy: The configuration of the indexing policy. By default, the indexing is - automatic for all document paths within the container. - :vartype indexing_policy: ~azure.mgmt.cosmosdb.models.IndexingPolicy - :ivar partition_key: The configuration of the partition key to be used for partitioning data - into multiple partitions. - :vartype partition_key: ~azure.mgmt.cosmosdb.models.ContainerPartitionKey - :ivar default_ttl: Default time to live. - :vartype default_ttl: int - :ivar unique_key_policy: The unique key policy configuration for specifying uniqueness - constraints on documents in the collection in the Azure Cosmos DB service. - :vartype unique_key_policy: ~azure.mgmt.cosmosdb.models.UniqueKeyPolicy - :ivar conflict_resolution_policy: The conflict resolution policy for the container. - :vartype conflict_resolution_policy: ~azure.mgmt.cosmosdb.models.ConflictResolutionPolicy - :ivar client_encryption_policy: The client encryption policy for the container. - :vartype client_encryption_policy: ~azure.mgmt.cosmosdb.models.ClientEncryptionPolicy - :ivar analytical_storage_ttl: Analytical TTL. - :vartype analytical_storage_ttl: int - :ivar restore_parameters: Parameters to indicate the information about the restore. - :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" - and "Restore". - :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - :ivar materialized_view_definition: The configuration for defining Materialized Views. This - must be specified only for creating a Materialized View container. - :vartype materialized_view_definition: ~azure.mgmt.cosmosdb.models.MaterializedViewDefinition - :ivar computed_properties: List of computed properties. - :vartype computed_properties: list[~azure.mgmt.cosmosdb.models.ComputedProperty] - """ - - _validation = { - "id": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "indexing_policy": {"key": "indexingPolicy", "type": "IndexingPolicy"}, - "partition_key": {"key": "partitionKey", "type": "ContainerPartitionKey"}, - "default_ttl": {"key": "defaultTtl", "type": "int"}, - "unique_key_policy": {"key": "uniqueKeyPolicy", "type": "UniqueKeyPolicy"}, - "conflict_resolution_policy": {"key": "conflictResolutionPolicy", "type": "ConflictResolutionPolicy"}, - "client_encryption_policy": {"key": "clientEncryptionPolicy", "type": "ClientEncryptionPolicy"}, - "analytical_storage_ttl": {"key": "analyticalStorageTtl", "type": "int"}, - "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, - "create_mode": {"key": "createMode", "type": "str"}, - "materialized_view_definition": {"key": "materializedViewDefinition", "type": "MaterializedViewDefinition"}, - "computed_properties": {"key": "computedProperties", "type": "[ComputedProperty]"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - indexing_policy: Optional["_models.IndexingPolicy"] = None, - partition_key: Optional["_models.ContainerPartitionKey"] = None, - default_ttl: Optional[int] = None, - unique_key_policy: Optional["_models.UniqueKeyPolicy"] = None, - conflict_resolution_policy: Optional["_models.ConflictResolutionPolicy"] = None, - client_encryption_policy: Optional["_models.ClientEncryptionPolicy"] = None, - analytical_storage_ttl: Optional[int] = None, - restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, - create_mode: Union[str, "_models.CreateMode"] = "Default", - materialized_view_definition: Optional["_models.MaterializedViewDefinition"] = None, - computed_properties: Optional[List["_models.ComputedProperty"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: Name of the Cosmos DB SQL container. Required. - :paramtype id: str - :keyword indexing_policy: The configuration of the indexing policy. By default, the indexing is - automatic for all document paths within the container. - :paramtype indexing_policy: ~azure.mgmt.cosmosdb.models.IndexingPolicy - :keyword partition_key: The configuration of the partition key to be used for partitioning data - into multiple partitions. - :paramtype partition_key: ~azure.mgmt.cosmosdb.models.ContainerPartitionKey - :keyword default_ttl: Default time to live. - :paramtype default_ttl: int - :keyword unique_key_policy: The unique key policy configuration for specifying uniqueness - constraints on documents in the collection in the Azure Cosmos DB service. - :paramtype unique_key_policy: ~azure.mgmt.cosmosdb.models.UniqueKeyPolicy - :keyword conflict_resolution_policy: The conflict resolution policy for the container. - :paramtype conflict_resolution_policy: ~azure.mgmt.cosmosdb.models.ConflictResolutionPolicy - :keyword client_encryption_policy: The client encryption policy for the container. - :paramtype client_encryption_policy: ~azure.mgmt.cosmosdb.models.ClientEncryptionPolicy - :keyword analytical_storage_ttl: Analytical TTL. - :paramtype analytical_storage_ttl: int - :keyword restore_parameters: Parameters to indicate the information about the restore. - :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: - "Default" and "Restore". - :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - :keyword materialized_view_definition: The configuration for defining Materialized Views. This - must be specified only for creating a Materialized View container. - :paramtype materialized_view_definition: ~azure.mgmt.cosmosdb.models.MaterializedViewDefinition - :keyword computed_properties: List of computed properties. - :paramtype computed_properties: list[~azure.mgmt.cosmosdb.models.ComputedProperty] - """ - super().__init__(**kwargs) - self.id = id - self.indexing_policy = indexing_policy - self.partition_key = partition_key - self.default_ttl = default_ttl - self.unique_key_policy = unique_key_policy - self.conflict_resolution_policy = conflict_resolution_policy - self.client_encryption_policy = client_encryption_policy - self.analytical_storage_ttl = analytical_storage_ttl - self.restore_parameters = restore_parameters - self.create_mode = create_mode - self.materialized_view_definition = materialized_view_definition - self.computed_properties = computed_properties - - -class RestorableSqlContainerPropertiesResourceContainer( - SqlContainerResource, ExtendedResourceProperties -): # pylint: disable=too-many-instance-attributes,name-too-long - """Cosmos DB SQL container resource object. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar rid: A system generated property. A unique identifier. - :vartype rid: str - :ivar ts: A system generated property that denotes the last updated timestamp of the resource. - :vartype ts: float - :ivar etag: A system generated property representing the resource etag required for optimistic - concurrency control. - :vartype etag: str - :ivar id: Name of the Cosmos DB SQL container. Required. - :vartype id: str - :ivar indexing_policy: The configuration of the indexing policy. By default, the indexing is - automatic for all document paths within the container. - :vartype indexing_policy: ~azure.mgmt.cosmosdb.models.IndexingPolicy - :ivar partition_key: The configuration of the partition key to be used for partitioning data - into multiple partitions. - :vartype partition_key: ~azure.mgmt.cosmosdb.models.ContainerPartitionKey - :ivar default_ttl: Default time to live. - :vartype default_ttl: int - :ivar unique_key_policy: The unique key policy configuration for specifying uniqueness - constraints on documents in the collection in the Azure Cosmos DB service. - :vartype unique_key_policy: ~azure.mgmt.cosmosdb.models.UniqueKeyPolicy - :ivar conflict_resolution_policy: The conflict resolution policy for the container. - :vartype conflict_resolution_policy: ~azure.mgmt.cosmosdb.models.ConflictResolutionPolicy - :ivar client_encryption_policy: The client encryption policy for the container. - :vartype client_encryption_policy: ~azure.mgmt.cosmosdb.models.ClientEncryptionPolicy - :ivar analytical_storage_ttl: Analytical TTL. - :vartype analytical_storage_ttl: int - :ivar restore_parameters: Parameters to indicate the information about the restore. - :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" - and "Restore". - :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - :ivar materialized_view_definition: The configuration for defining Materialized Views. This - must be specified only for creating a Materialized View container. - :vartype materialized_view_definition: ~azure.mgmt.cosmosdb.models.MaterializedViewDefinition - :ivar computed_properties: List of computed properties. - :vartype computed_properties: list[~azure.mgmt.cosmosdb.models.ComputedProperty] - :ivar self_property: A system generated property that specifies the addressable path of the - container resource. - :vartype self_property: str - """ - - _validation = { - "rid": {"readonly": True}, - "ts": {"readonly": True}, - "etag": {"readonly": True}, - "id": {"required": True}, - "self_property": {"readonly": True}, - } - - _attribute_map = { - "rid": {"key": "_rid", "type": "str"}, - "ts": {"key": "_ts", "type": "float"}, - "etag": {"key": "_etag", "type": "str"}, - "id": {"key": "id", "type": "str"}, - "indexing_policy": {"key": "indexingPolicy", "type": "IndexingPolicy"}, - "partition_key": {"key": "partitionKey", "type": "ContainerPartitionKey"}, - "default_ttl": {"key": "defaultTtl", "type": "int"}, - "unique_key_policy": {"key": "uniqueKeyPolicy", "type": "UniqueKeyPolicy"}, - "conflict_resolution_policy": {"key": "conflictResolutionPolicy", "type": "ConflictResolutionPolicy"}, - "client_encryption_policy": {"key": "clientEncryptionPolicy", "type": "ClientEncryptionPolicy"}, - "analytical_storage_ttl": {"key": "analyticalStorageTtl", "type": "int"}, - "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, - "create_mode": {"key": "createMode", "type": "str"}, - "materialized_view_definition": {"key": "materializedViewDefinition", "type": "MaterializedViewDefinition"}, - "computed_properties": {"key": "computedProperties", "type": "[ComputedProperty]"}, - "self_property": {"key": "_self", "type": "str"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - indexing_policy: Optional["_models.IndexingPolicy"] = None, - partition_key: Optional["_models.ContainerPartitionKey"] = None, - default_ttl: Optional[int] = None, - unique_key_policy: Optional["_models.UniqueKeyPolicy"] = None, - conflict_resolution_policy: Optional["_models.ConflictResolutionPolicy"] = None, - client_encryption_policy: Optional["_models.ClientEncryptionPolicy"] = None, - analytical_storage_ttl: Optional[int] = None, - restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, - create_mode: Union[str, "_models.CreateMode"] = "Default", - materialized_view_definition: Optional["_models.MaterializedViewDefinition"] = None, - computed_properties: Optional[List["_models.ComputedProperty"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: Name of the Cosmos DB SQL container. Required. - :paramtype id: str - :keyword indexing_policy: The configuration of the indexing policy. By default, the indexing is - automatic for all document paths within the container. - :paramtype indexing_policy: ~azure.mgmt.cosmosdb.models.IndexingPolicy - :keyword partition_key: The configuration of the partition key to be used for partitioning data - into multiple partitions. - :paramtype partition_key: ~azure.mgmt.cosmosdb.models.ContainerPartitionKey - :keyword default_ttl: Default time to live. - :paramtype default_ttl: int - :keyword unique_key_policy: The unique key policy configuration for specifying uniqueness - constraints on documents in the collection in the Azure Cosmos DB service. - :paramtype unique_key_policy: ~azure.mgmt.cosmosdb.models.UniqueKeyPolicy - :keyword conflict_resolution_policy: The conflict resolution policy for the container. - :paramtype conflict_resolution_policy: ~azure.mgmt.cosmosdb.models.ConflictResolutionPolicy - :keyword client_encryption_policy: The client encryption policy for the container. - :paramtype client_encryption_policy: ~azure.mgmt.cosmosdb.models.ClientEncryptionPolicy - :keyword analytical_storage_ttl: Analytical TTL. - :paramtype analytical_storage_ttl: int - :keyword restore_parameters: Parameters to indicate the information about the restore. - :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: - "Default" and "Restore". - :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - :keyword materialized_view_definition: The configuration for defining Materialized Views. This - must be specified only for creating a Materialized View container. - :paramtype materialized_view_definition: ~azure.mgmt.cosmosdb.models.MaterializedViewDefinition - :keyword computed_properties: List of computed properties. - :paramtype computed_properties: list[~azure.mgmt.cosmosdb.models.ComputedProperty] - """ - super().__init__( - id=id, - indexing_policy=indexing_policy, - partition_key=partition_key, - default_ttl=default_ttl, - unique_key_policy=unique_key_policy, - conflict_resolution_policy=conflict_resolution_policy, - client_encryption_policy=client_encryption_policy, - analytical_storage_ttl=analytical_storage_ttl, - restore_parameters=restore_parameters, - create_mode=create_mode, - materialized_view_definition=materialized_view_definition, - computed_properties=computed_properties, - **kwargs - ) - self.rid = None - self.ts = None - self.etag = None - self.self_property = None - self.id = id - self.indexing_policy = indexing_policy - self.partition_key = partition_key - self.default_ttl = default_ttl - self.unique_key_policy = unique_key_policy - self.conflict_resolution_policy = conflict_resolution_policy - self.client_encryption_policy = client_encryption_policy - self.analytical_storage_ttl = analytical_storage_ttl - self.restore_parameters = restore_parameters - self.create_mode = create_mode - self.materialized_view_definition = materialized_view_definition - self.computed_properties = computed_properties - - -class RestorableSqlContainersListResult(_serialization.Model): - """The List operation response, that contains the SQL container events and their properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of SQL container events and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.RestorableSqlContainerGetResult] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[RestorableSqlContainerGetResult]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class RestorableSqlDatabaseGetResult(_serialization.Model): - """An Azure Cosmos DB SQL database event. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource Identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar resource: The resource of an Azure Cosmos DB SQL database event. - :vartype resource: ~azure.mgmt.cosmosdb.models.RestorableSqlDatabasePropertiesResource - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "resource": {"key": "properties.resource", "type": "RestorableSqlDatabasePropertiesResource"}, - } - - def __init__( - self, *, resource: Optional["_models.RestorableSqlDatabasePropertiesResource"] = None, **kwargs: Any - ) -> None: - """ - :keyword resource: The resource of an Azure Cosmos DB SQL database event. - :paramtype resource: ~azure.mgmt.cosmosdb.models.RestorableSqlDatabasePropertiesResource - """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.resource = resource - - -class RestorableSqlDatabasePropertiesResource(_serialization.Model): - """The resource of an Azure Cosmos DB SQL database event. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar rid: A system generated property. A unique identifier. - :vartype rid: str - :ivar operation_type: The operation type of this database event. Known values are: "Create", - "Replace", "Delete", "Recreate", and "SystemOperation". - :vartype operation_type: str or ~azure.mgmt.cosmosdb.models.OperationType - :ivar can_undelete: A state of this database to identify if this database is restorable in same - account. - :vartype can_undelete: str - :ivar can_undelete_reason: The reason why this database can not be restored in same account. - :vartype can_undelete_reason: str - :ivar event_timestamp: The time when this database event happened. - :vartype event_timestamp: str - :ivar owner_id: The name of the SQL database. - :vartype owner_id: str - :ivar owner_resource_id: The resource ID of the SQL database. - :vartype owner_resource_id: str - :ivar database: Cosmos DB SQL database resource object. - :vartype database: ~azure.mgmt.cosmosdb.models.RestorableSqlDatabasePropertiesResourceDatabase - """ - - _validation = { - "rid": {"readonly": True}, - "operation_type": {"readonly": True}, - "can_undelete": {"readonly": True}, - "can_undelete_reason": {"readonly": True}, - "event_timestamp": {"readonly": True}, - "owner_id": {"readonly": True}, - "owner_resource_id": {"readonly": True}, - } - - _attribute_map = { - "rid": {"key": "_rid", "type": "str"}, - "operation_type": {"key": "operationType", "type": "str"}, - "can_undelete": {"key": "canUndelete", "type": "str"}, - "can_undelete_reason": {"key": "canUndeleteReason", "type": "str"}, - "event_timestamp": {"key": "eventTimestamp", "type": "str"}, - "owner_id": {"key": "ownerId", "type": "str"}, - "owner_resource_id": {"key": "ownerResourceId", "type": "str"}, - "database": {"key": "database", "type": "RestorableSqlDatabasePropertiesResourceDatabase"}, - } - - def __init__( - self, *, database: Optional["_models.RestorableSqlDatabasePropertiesResourceDatabase"] = None, **kwargs: Any - ) -> None: - """ - :keyword database: Cosmos DB SQL database resource object. - :paramtype database: - ~azure.mgmt.cosmosdb.models.RestorableSqlDatabasePropertiesResourceDatabase - """ - super().__init__(**kwargs) - self.rid = None - self.operation_type = None - self.can_undelete = None - self.can_undelete_reason = None - self.event_timestamp = None - self.owner_id = None - self.owner_resource_id = None - self.database = database - - -class SqlDatabaseResource(_serialization.Model): - """Cosmos DB SQL database resource object. - - All required parameters must be populated in order to send to server. - - :ivar id: Name of the Cosmos DB SQL database. Required. - :vartype id: str - :ivar restore_parameters: Parameters to indicate the information about the restore. - :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" - and "Restore". - :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - """ - - _validation = { - "id": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, - "create_mode": {"key": "createMode", "type": "str"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, - create_mode: Union[str, "_models.CreateMode"] = "Default", - **kwargs: Any - ) -> None: - """ - :keyword id: Name of the Cosmos DB SQL database. Required. - :paramtype id: str - :keyword restore_parameters: Parameters to indicate the information about the restore. - :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: - "Default" and "Restore". - :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - """ - super().__init__(**kwargs) - self.id = id - self.restore_parameters = restore_parameters - self.create_mode = create_mode - - -class RestorableSqlDatabasePropertiesResourceDatabase( - SqlDatabaseResource, ExtendedResourceProperties -): # pylint: disable=name-too-long - """Cosmos DB SQL database resource object. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar rid: A system generated property. A unique identifier. - :vartype rid: str - :ivar ts: A system generated property that denotes the last updated timestamp of the resource. - :vartype ts: float - :ivar etag: A system generated property representing the resource etag required for optimistic - concurrency control. - :vartype etag: str - :ivar id: Name of the Cosmos DB SQL database. Required. - :vartype id: str - :ivar restore_parameters: Parameters to indicate the information about the restore. - :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" - and "Restore". - :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - :ivar colls: A system generated property that specified the addressable path of the collections - resource. - :vartype colls: str - :ivar users: A system generated property that specifies the addressable path of the users - resource. - :vartype users: str - :ivar self_property: A system generated property that specifies the addressable path of the - database resource. - :vartype self_property: str - """ - - _validation = { - "rid": {"readonly": True}, - "ts": {"readonly": True}, - "etag": {"readonly": True}, - "id": {"required": True}, - "colls": {"readonly": True}, - "users": {"readonly": True}, - "self_property": {"readonly": True}, - } - - _attribute_map = { - "rid": {"key": "_rid", "type": "str"}, - "ts": {"key": "_ts", "type": "float"}, - "etag": {"key": "_etag", "type": "str"}, - "id": {"key": "id", "type": "str"}, - "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, - "create_mode": {"key": "createMode", "type": "str"}, - "colls": {"key": "_colls", "type": "str"}, - "users": {"key": "_users", "type": "str"}, - "self_property": {"key": "_self", "type": "str"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, - create_mode: Union[str, "_models.CreateMode"] = "Default", - **kwargs: Any - ) -> None: - """ - :keyword id: Name of the Cosmos DB SQL database. Required. - :paramtype id: str - :keyword restore_parameters: Parameters to indicate the information about the restore. - :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: - "Default" and "Restore". - :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - """ - super().__init__(id=id, restore_parameters=restore_parameters, create_mode=create_mode, **kwargs) - self.rid = None - self.ts = None - self.etag = None - self.colls = None - self.users = None - self.self_property = None - self.id = id - self.restore_parameters = restore_parameters - self.create_mode = create_mode - - -class RestorableSqlDatabasesListResult(_serialization.Model): - """The List operation response, that contains the SQL database events and their properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of SQL database events and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.RestorableSqlDatabaseGetResult] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[RestorableSqlDatabaseGetResult]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class RestorableSqlResourcesGetResult(_serialization.Model): - """Specific Databases to restore. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar database_name: The name of the database available for restore. - :vartype database_name: str - :ivar collection_names: The names of the collections available for restore. - :vartype collection_names: list[str] - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "database_name": {"key": "databaseName", "type": "str"}, - "collection_names": {"key": "collectionNames", "type": "[str]"}, - } - - def __init__( - self, *, database_name: Optional[str] = None, collection_names: Optional[List[str]] = None, **kwargs: Any - ) -> None: - """ - :keyword database_name: The name of the database available for restore. - :paramtype database_name: str - :keyword collection_names: The names of the collections available for restore. - :paramtype collection_names: list[str] - """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.database_name = database_name - self.collection_names = collection_names - - -class RestorableSqlResourcesListResult(_serialization.Model): - """The List operation response, that contains the restorable SQL resources. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of restorable SQL resources, including the database and collection names. - :vartype value: list[~azure.mgmt.cosmosdb.models.RestorableSqlResourcesGetResult] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[RestorableSqlResourcesGetResult]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class RestorableTableGetResult(_serialization.Model): - """An Azure Cosmos DB Table event. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource Identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar resource: The resource of an Azure Cosmos DB Table event. - :vartype resource: ~azure.mgmt.cosmosdb.models.RestorableTablePropertiesResource - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "resource": {"key": "properties.resource", "type": "RestorableTablePropertiesResource"}, - } - - def __init__( - self, *, resource: Optional["_models.RestorableTablePropertiesResource"] = None, **kwargs: Any - ) -> None: - """ - :keyword resource: The resource of an Azure Cosmos DB Table event. - :paramtype resource: ~azure.mgmt.cosmosdb.models.RestorableTablePropertiesResource - """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.resource = resource - - -class RestorableTablePropertiesResource(_serialization.Model): - """The resource of an Azure Cosmos DB Table event. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar rid: A system generated property. A unique identifier. - :vartype rid: str - :ivar operation_type: The operation type of this table event. Known values are: "Create", - "Replace", "Delete", "Recreate", and "SystemOperation". - :vartype operation_type: str or ~azure.mgmt.cosmosdb.models.OperationType - :ivar can_undelete: A state of this table to identify if this table is restorable in same - account. - :vartype can_undelete: str - :ivar can_undelete_reason: The reason why this table can not be restored in same account. - :vartype can_undelete_reason: str - :ivar event_timestamp: The time when this table event happened. - :vartype event_timestamp: str - :ivar owner_id: The name of this Table. - :vartype owner_id: str - :ivar owner_resource_id: The resource ID of this Table. - :vartype owner_resource_id: str - """ - - _validation = { - "rid": {"readonly": True}, - "operation_type": {"readonly": True}, - "can_undelete": {"readonly": True}, - "can_undelete_reason": {"readonly": True}, - "event_timestamp": {"readonly": True}, - "owner_id": {"readonly": True}, - "owner_resource_id": {"readonly": True}, - } - - _attribute_map = { - "rid": {"key": "_rid", "type": "str"}, - "operation_type": {"key": "operationType", "type": "str"}, - "can_undelete": {"key": "canUndelete", "type": "str"}, - "can_undelete_reason": {"key": "canUndeleteReason", "type": "str"}, - "event_timestamp": {"key": "eventTimestamp", "type": "str"}, - "owner_id": {"key": "ownerId", "type": "str"}, - "owner_resource_id": {"key": "ownerResourceId", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.rid = None - self.operation_type = None - self.can_undelete = None - self.can_undelete_reason = None - self.event_timestamp = None - self.owner_id = None - self.owner_resource_id = None - - -class RestorableTableResourcesGetResult(_serialization.Model): - """Specific Databases to restore. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the Table. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - - -class RestorableTableResourcesListResult(_serialization.Model): - """List of restorable table names. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of restorable table names. - :vartype value: list[~azure.mgmt.cosmosdb.models.RestorableTableResourcesGetResult] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[RestorableTableResourcesGetResult]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class RestorableTablesListResult(_serialization.Model): - """The List operation response, that contains the Table events and their properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of Table events and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.RestorableTableGetResult] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[RestorableTableGetResult]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class RestoreParameters(RestoreParametersBase): - """Parameters to indicate the information about the restore. - - :ivar restore_source: The id of the restorable database account from which the restore has to - be initiated. For example: - /subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{restorableDatabaseAccountName}. # pylint: disable=line-too-long - :vartype restore_source: str - :ivar restore_timestamp_in_utc: Time to which the account has to be restored (ISO-8601 format). - :vartype restore_timestamp_in_utc: ~datetime.datetime - :ivar restore_with_ttl_disabled: Specifies whether the restored account will have Time-To-Live - disabled upon the successful restore. - :vartype restore_with_ttl_disabled: bool - :ivar restore_mode: Describes the mode of the restore. "PointInTime" - :vartype restore_mode: str or ~azure.mgmt.cosmosdb.models.RestoreMode - :ivar databases_to_restore: List of specific databases available for restore. - :vartype databases_to_restore: list[~azure.mgmt.cosmosdb.models.DatabaseRestoreResource] - :ivar gremlin_databases_to_restore: List of specific gremlin databases available for restore. - :vartype gremlin_databases_to_restore: - list[~azure.mgmt.cosmosdb.models.GremlinDatabaseRestoreResource] - :ivar tables_to_restore: List of specific tables available for restore. - :vartype tables_to_restore: list[str] - :ivar source_backup_location: The source backup location for restore. - :vartype source_backup_location: str - """ - - _attribute_map = { - "restore_source": {"key": "restoreSource", "type": "str"}, - "restore_timestamp_in_utc": {"key": "restoreTimestampInUtc", "type": "iso-8601"}, - "restore_with_ttl_disabled": {"key": "restoreWithTtlDisabled", "type": "bool"}, - "restore_mode": {"key": "restoreMode", "type": "str"}, - "databases_to_restore": {"key": "databasesToRestore", "type": "[DatabaseRestoreResource]"}, - "gremlin_databases_to_restore": { - "key": "gremlinDatabasesToRestore", - "type": "[GremlinDatabaseRestoreResource]", - }, - "tables_to_restore": {"key": "tablesToRestore", "type": "[str]"}, - "source_backup_location": {"key": "sourceBackupLocation", "type": "str"}, - } - - def __init__( - self, - *, - restore_source: Optional[str] = None, - restore_timestamp_in_utc: Optional[datetime.datetime] = None, - restore_with_ttl_disabled: Optional[bool] = None, - restore_mode: Optional[Union[str, "_models.RestoreMode"]] = None, - databases_to_restore: Optional[List["_models.DatabaseRestoreResource"]] = None, - gremlin_databases_to_restore: Optional[List["_models.GremlinDatabaseRestoreResource"]] = None, - tables_to_restore: Optional[List[str]] = None, - source_backup_location: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword restore_source: The id of the restorable database account from which the restore has - to be initiated. For example: - /subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{restorableDatabaseAccountName}. # pylint: disable=line-too-long - :paramtype restore_source: str - :keyword restore_timestamp_in_utc: Time to which the account has to be restored (ISO-8601 - format). - :paramtype restore_timestamp_in_utc: ~datetime.datetime - :keyword restore_with_ttl_disabled: Specifies whether the restored account will have - Time-To-Live disabled upon the successful restore. - :paramtype restore_with_ttl_disabled: bool - :keyword restore_mode: Describes the mode of the restore. "PointInTime" - :paramtype restore_mode: str or ~azure.mgmt.cosmosdb.models.RestoreMode - :keyword databases_to_restore: List of specific databases available for restore. - :paramtype databases_to_restore: list[~azure.mgmt.cosmosdb.models.DatabaseRestoreResource] - :keyword gremlin_databases_to_restore: List of specific gremlin databases available for - restore. - :paramtype gremlin_databases_to_restore: - list[~azure.mgmt.cosmosdb.models.GremlinDatabaseRestoreResource] - :keyword tables_to_restore: List of specific tables available for restore. - :paramtype tables_to_restore: list[str] - :keyword source_backup_location: The source backup location for restore. - :paramtype source_backup_location: str - """ - super().__init__( - restore_source=restore_source, - restore_timestamp_in_utc=restore_timestamp_in_utc, - restore_with_ttl_disabled=restore_with_ttl_disabled, - **kwargs - ) - self.restore_mode = restore_mode - self.databases_to_restore = databases_to_restore - self.gremlin_databases_to_restore = gremlin_databases_to_restore - self.tables_to_restore = tables_to_restore - self.source_backup_location = source_backup_location - - -class RetrieveThroughputParameters(ARMResourceProperties): - """Cosmos DB retrieve throughput parameters object. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: The standard JSON format of a resource throughput. Required. - :vartype resource: ~azure.mgmt.cosmosdb.models.RetrieveThroughputPropertiesResource - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "resource": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "RetrieveThroughputPropertiesResource"}, - } - - def __init__( - self, - *, - resource: "_models.RetrieveThroughputPropertiesResource", - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: The standard JSON format of a resource throughput. Required. - :paramtype resource: ~azure.mgmt.cosmosdb.models.RetrieveThroughputPropertiesResource - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - - -class RetrieveThroughputPropertiesResource(_serialization.Model): - """Resource to retrieve throughput information for Cosmos DB resource. - - All required parameters must be populated in order to send to server. - - :ivar physical_partition_ids: Array of PhysicalPartitionId objects. Required. - :vartype physical_partition_ids: list[~azure.mgmt.cosmosdb.models.PhysicalPartitionId] - """ - - _validation = { - "physical_partition_ids": {"required": True}, - } - - _attribute_map = { - "physical_partition_ids": {"key": "physicalPartitionIds", "type": "[PhysicalPartitionId]"}, - } - - def __init__(self, *, physical_partition_ids: List["_models.PhysicalPartitionId"], **kwargs: Any) -> None: - """ - :keyword physical_partition_ids: Array of PhysicalPartitionId objects. Required. - :paramtype physical_partition_ids: list[~azure.mgmt.cosmosdb.models.PhysicalPartitionId] - """ - super().__init__(**kwargs) - self.physical_partition_ids = physical_partition_ids - - -class Role(_serialization.Model): - """The set of roles permitted through this Role Definition. - - :ivar db: The database name the role is applied. - :vartype db: str - :ivar role: The role name. - :vartype role: str - """ - - _attribute_map = { - "db": {"key": "db", "type": "str"}, - "role": {"key": "role", "type": "str"}, - } - - def __init__(self, *, db: Optional[str] = None, role: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword db: The database name the role is applied. - :paramtype db: str - :keyword role: The role name. - :paramtype role: str - """ - super().__init__(**kwargs) - self.db = db - self.role = role - - -class SeedNode(_serialization.Model): - """SeedNode. - - :ivar ip_address: IP address of this seed node. - :vartype ip_address: str - """ - - _attribute_map = { - "ip_address": {"key": "ipAddress", "type": "str"}, - } - - def __init__(self, *, ip_address: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword ip_address: IP address of this seed node. - :paramtype ip_address: str - """ - super().__init__(**kwargs) - self.ip_address = ip_address - - -class ServiceResource(ARMProxyResource): - """Properties for the database account. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the database account. - :vartype id: str - :ivar name: The name of the database account. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar properties: Services response resource. - :vartype properties: ~azure.mgmt.cosmosdb.models.ServiceResourceProperties - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "properties": {"key": "properties", "type": "ServiceResourceProperties"}, - } - - def __init__(self, *, properties: Optional["_models.ServiceResourceProperties"] = None, **kwargs: Any) -> None: - """ - :keyword properties: Services response resource. - :paramtype properties: ~azure.mgmt.cosmosdb.models.ServiceResourceProperties - """ - super().__init__(**kwargs) - self.properties = properties - - -class ServiceResourceCreateUpdateParameters(_serialization.Model): - """Parameters for Create or Update request for ServiceResource. - - :ivar properties: Properties in ServiceResourceCreateUpdateParameters. - :vartype properties: ~azure.mgmt.cosmosdb.models.ServiceResourceCreateUpdateProperties - """ - - _attribute_map = { - "properties": {"key": "properties", "type": "ServiceResourceCreateUpdateProperties"}, - } - - def __init__( - self, *, properties: Optional["_models.ServiceResourceCreateUpdateProperties"] = None, **kwargs: Any - ) -> None: - """ - :keyword properties: Properties in ServiceResourceCreateUpdateParameters. - :paramtype properties: ~azure.mgmt.cosmosdb.models.ServiceResourceCreateUpdateProperties - """ - super().__init__(**kwargs) - self.properties = properties - - -class ServiceResourceListResult(_serialization.Model): - """The List operation response, that contains the Service Resource and their properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of Service Resource and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.ServiceResource] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[ServiceResource]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class SpatialSpec(_serialization.Model): - """SpatialSpec. - - :ivar path: The path for which the indexing behavior applies to. Index paths typically start - with root and end with wildcard (/path/*). - :vartype path: str - :ivar types: List of path's spatial type. - :vartype types: list[str or ~azure.mgmt.cosmosdb.models.SpatialType] - """ - - _attribute_map = { - "path": {"key": "path", "type": "str"}, - "types": {"key": "types", "type": "[str]"}, - } - - def __init__( - self, - *, - path: Optional[str] = None, - types: Optional[List[Union[str, "_models.SpatialType"]]] = None, - **kwargs: Any - ) -> None: - """ - :keyword path: The path for which the indexing behavior applies to. Index paths typically start - with root and end with wildcard (/path/*). - :paramtype path: str - :keyword types: List of path's spatial type. - :paramtype types: list[str or ~azure.mgmt.cosmosdb.models.SpatialType] - """ - super().__init__(**kwargs) - self.path = path - self.types = types - - -class SqlContainerCreateUpdateParameters(ARMResourceProperties): - """Parameters to create and update Cosmos DB container. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: The standard JSON format of a container. Required. - :vartype resource: ~azure.mgmt.cosmosdb.models.SqlContainerResource - :ivar options: A key-value pair of options to be applied for the request. This corresponds to - the headers sent with the request. - :vartype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "resource": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "SqlContainerResource"}, - "options": {"key": "properties.options", "type": "CreateUpdateOptions"}, - } - - def __init__( - self, - *, - resource: "_models.SqlContainerResource", - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - options: Optional["_models.CreateUpdateOptions"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: The standard JSON format of a container. Required. - :paramtype resource: ~azure.mgmt.cosmosdb.models.SqlContainerResource - :keyword options: A key-value pair of options to be applied for the request. This corresponds - to the headers sent with the request. - :paramtype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - self.options = options - - -class SqlContainerGetPropertiesOptions(OptionsResource): - """SqlContainerGetPropertiesOptions. - - :ivar throughput: Value of the Cosmos DB resource throughput or autoscaleSettings. Use the - ThroughputSetting resource when retrieving offer details. - :vartype throughput: int - :ivar autoscale_settings: Specifies the Autoscale settings. - :vartype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettings - """ - - -class SqlContainerGetPropertiesResource( - SqlContainerResource, ExtendedResourceProperties -): # pylint: disable=too-many-instance-attributes - """SqlContainerGetPropertiesResource. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar rid: A system generated property. A unique identifier. - :vartype rid: str - :ivar ts: A system generated property that denotes the last updated timestamp of the resource. - :vartype ts: float - :ivar etag: A system generated property representing the resource etag required for optimistic - concurrency control. - :vartype etag: str - :ivar id: Name of the Cosmos DB SQL container. Required. - :vartype id: str - :ivar indexing_policy: The configuration of the indexing policy. By default, the indexing is - automatic for all document paths within the container. - :vartype indexing_policy: ~azure.mgmt.cosmosdb.models.IndexingPolicy - :ivar partition_key: The configuration of the partition key to be used for partitioning data - into multiple partitions. - :vartype partition_key: ~azure.mgmt.cosmosdb.models.ContainerPartitionKey - :ivar default_ttl: Default time to live. - :vartype default_ttl: int - :ivar unique_key_policy: The unique key policy configuration for specifying uniqueness - constraints on documents in the collection in the Azure Cosmos DB service. - :vartype unique_key_policy: ~azure.mgmt.cosmosdb.models.UniqueKeyPolicy - :ivar conflict_resolution_policy: The conflict resolution policy for the container. - :vartype conflict_resolution_policy: ~azure.mgmt.cosmosdb.models.ConflictResolutionPolicy - :ivar client_encryption_policy: The client encryption policy for the container. - :vartype client_encryption_policy: ~azure.mgmt.cosmosdb.models.ClientEncryptionPolicy - :ivar analytical_storage_ttl: Analytical TTL. - :vartype analytical_storage_ttl: int - :ivar restore_parameters: Parameters to indicate the information about the restore. - :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" - and "Restore". - :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - :ivar materialized_view_definition: The configuration for defining Materialized Views. This - must be specified only for creating a Materialized View container. - :vartype materialized_view_definition: ~azure.mgmt.cosmosdb.models.MaterializedViewDefinition - :ivar computed_properties: List of computed properties. - :vartype computed_properties: list[~azure.mgmt.cosmosdb.models.ComputedProperty] - """ - - _validation = { - "rid": {"readonly": True}, - "ts": {"readonly": True}, - "etag": {"readonly": True}, - "id": {"required": True}, - } - - _attribute_map = { - "rid": {"key": "_rid", "type": "str"}, - "ts": {"key": "_ts", "type": "float"}, - "etag": {"key": "_etag", "type": "str"}, - "id": {"key": "id", "type": "str"}, - "indexing_policy": {"key": "indexingPolicy", "type": "IndexingPolicy"}, - "partition_key": {"key": "partitionKey", "type": "ContainerPartitionKey"}, - "default_ttl": {"key": "defaultTtl", "type": "int"}, - "unique_key_policy": {"key": "uniqueKeyPolicy", "type": "UniqueKeyPolicy"}, - "conflict_resolution_policy": {"key": "conflictResolutionPolicy", "type": "ConflictResolutionPolicy"}, - "client_encryption_policy": {"key": "clientEncryptionPolicy", "type": "ClientEncryptionPolicy"}, - "analytical_storage_ttl": {"key": "analyticalStorageTtl", "type": "int"}, - "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, - "create_mode": {"key": "createMode", "type": "str"}, - "materialized_view_definition": {"key": "materializedViewDefinition", "type": "MaterializedViewDefinition"}, - "computed_properties": {"key": "computedProperties", "type": "[ComputedProperty]"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - indexing_policy: Optional["_models.IndexingPolicy"] = None, - partition_key: Optional["_models.ContainerPartitionKey"] = None, - default_ttl: Optional[int] = None, - unique_key_policy: Optional["_models.UniqueKeyPolicy"] = None, - conflict_resolution_policy: Optional["_models.ConflictResolutionPolicy"] = None, - client_encryption_policy: Optional["_models.ClientEncryptionPolicy"] = None, - analytical_storage_ttl: Optional[int] = None, - restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, - create_mode: Union[str, "_models.CreateMode"] = "Default", - materialized_view_definition: Optional["_models.MaterializedViewDefinition"] = None, - computed_properties: Optional[List["_models.ComputedProperty"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: Name of the Cosmos DB SQL container. Required. - :paramtype id: str - :keyword indexing_policy: The configuration of the indexing policy. By default, the indexing is - automatic for all document paths within the container. - :paramtype indexing_policy: ~azure.mgmt.cosmosdb.models.IndexingPolicy - :keyword partition_key: The configuration of the partition key to be used for partitioning data - into multiple partitions. - :paramtype partition_key: ~azure.mgmt.cosmosdb.models.ContainerPartitionKey - :keyword default_ttl: Default time to live. - :paramtype default_ttl: int - :keyword unique_key_policy: The unique key policy configuration for specifying uniqueness - constraints on documents in the collection in the Azure Cosmos DB service. - :paramtype unique_key_policy: ~azure.mgmt.cosmosdb.models.UniqueKeyPolicy - :keyword conflict_resolution_policy: The conflict resolution policy for the container. - :paramtype conflict_resolution_policy: ~azure.mgmt.cosmosdb.models.ConflictResolutionPolicy - :keyword client_encryption_policy: The client encryption policy for the container. - :paramtype client_encryption_policy: ~azure.mgmt.cosmosdb.models.ClientEncryptionPolicy - :keyword analytical_storage_ttl: Analytical TTL. - :paramtype analytical_storage_ttl: int - :keyword restore_parameters: Parameters to indicate the information about the restore. - :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: - "Default" and "Restore". - :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - :keyword materialized_view_definition: The configuration for defining Materialized Views. This - must be specified only for creating a Materialized View container. - :paramtype materialized_view_definition: ~azure.mgmt.cosmosdb.models.MaterializedViewDefinition - :keyword computed_properties: List of computed properties. - :paramtype computed_properties: list[~azure.mgmt.cosmosdb.models.ComputedProperty] - """ - super().__init__( - id=id, - indexing_policy=indexing_policy, - partition_key=partition_key, - default_ttl=default_ttl, - unique_key_policy=unique_key_policy, - conflict_resolution_policy=conflict_resolution_policy, - client_encryption_policy=client_encryption_policy, - analytical_storage_ttl=analytical_storage_ttl, - restore_parameters=restore_parameters, - create_mode=create_mode, - materialized_view_definition=materialized_view_definition, - computed_properties=computed_properties, - **kwargs - ) - self.rid = None - self.ts = None - self.etag = None - self.id = id - self.indexing_policy = indexing_policy - self.partition_key = partition_key - self.default_ttl = default_ttl - self.unique_key_policy = unique_key_policy - self.conflict_resolution_policy = conflict_resolution_policy - self.client_encryption_policy = client_encryption_policy - self.analytical_storage_ttl = analytical_storage_ttl - self.restore_parameters = restore_parameters - self.create_mode = create_mode - self.materialized_view_definition = materialized_view_definition - self.computed_properties = computed_properties - - -class SqlContainerGetResults(ARMResourceProperties): - """An Azure Cosmos DB container. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: - :vartype resource: ~azure.mgmt.cosmosdb.models.SqlContainerGetPropertiesResource - :ivar options: - :vartype options: ~azure.mgmt.cosmosdb.models.SqlContainerGetPropertiesOptions - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "SqlContainerGetPropertiesResource"}, - "options": {"key": "properties.options", "type": "SqlContainerGetPropertiesOptions"}, - } - - def __init__( - self, - *, - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - resource: Optional["_models.SqlContainerGetPropertiesResource"] = None, - options: Optional["_models.SqlContainerGetPropertiesOptions"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: - :paramtype resource: ~azure.mgmt.cosmosdb.models.SqlContainerGetPropertiesResource - :keyword options: - :paramtype options: ~azure.mgmt.cosmosdb.models.SqlContainerGetPropertiesOptions - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - self.options = options - - -class SqlContainerListResult(_serialization.Model): - """The List operation response, that contains the containers and their properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of containers and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.SqlContainerGetResults] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[SqlContainerGetResults]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class SqlDatabaseCreateUpdateParameters(ARMResourceProperties): - """Parameters to create and update Cosmos DB SQL database. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: The standard JSON format of a SQL database. Required. - :vartype resource: ~azure.mgmt.cosmosdb.models.SqlDatabaseResource - :ivar options: A key-value pair of options to be applied for the request. This corresponds to - the headers sent with the request. - :vartype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "resource": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "SqlDatabaseResource"}, - "options": {"key": "properties.options", "type": "CreateUpdateOptions"}, - } - - def __init__( - self, - *, - resource: "_models.SqlDatabaseResource", - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - options: Optional["_models.CreateUpdateOptions"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: The standard JSON format of a SQL database. Required. - :paramtype resource: ~azure.mgmt.cosmosdb.models.SqlDatabaseResource - :keyword options: A key-value pair of options to be applied for the request. This corresponds - to the headers sent with the request. - :paramtype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - self.options = options - - -class SqlDatabaseGetPropertiesOptions(OptionsResource): - """SqlDatabaseGetPropertiesOptions. - - :ivar throughput: Value of the Cosmos DB resource throughput or autoscaleSettings. Use the - ThroughputSetting resource when retrieving offer details. - :vartype throughput: int - :ivar autoscale_settings: Specifies the Autoscale settings. - :vartype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettings - """ - - -class SqlDatabaseGetPropertiesResource(SqlDatabaseResource, ExtendedResourceProperties): - """SqlDatabaseGetPropertiesResource. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar rid: A system generated property. A unique identifier. - :vartype rid: str - :ivar ts: A system generated property that denotes the last updated timestamp of the resource. - :vartype ts: float - :ivar etag: A system generated property representing the resource etag required for optimistic - concurrency control. - :vartype etag: str - :ivar id: Name of the Cosmos DB SQL database. Required. - :vartype id: str - :ivar restore_parameters: Parameters to indicate the information about the restore. - :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" - and "Restore". - :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - :ivar colls: A system generated property that specified the addressable path of the collections - resource. - :vartype colls: str - :ivar users: A system generated property that specifies the addressable path of the users - resource. - :vartype users: str - """ - - _validation = { - "rid": {"readonly": True}, - "ts": {"readonly": True}, - "etag": {"readonly": True}, - "id": {"required": True}, - } - - _attribute_map = { - "rid": {"key": "_rid", "type": "str"}, - "ts": {"key": "_ts", "type": "float"}, - "etag": {"key": "_etag", "type": "str"}, - "id": {"key": "id", "type": "str"}, - "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, - "create_mode": {"key": "createMode", "type": "str"}, - "colls": {"key": "_colls", "type": "str"}, - "users": {"key": "_users", "type": "str"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, - create_mode: Union[str, "_models.CreateMode"] = "Default", - colls: Optional[str] = None, - users: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: Name of the Cosmos DB SQL database. Required. - :paramtype id: str - :keyword restore_parameters: Parameters to indicate the information about the restore. - :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: - "Default" and "Restore". - :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - :keyword colls: A system generated property that specified the addressable path of the - collections resource. - :paramtype colls: str - :keyword users: A system generated property that specifies the addressable path of the users - resource. - :paramtype users: str - """ - super().__init__(id=id, restore_parameters=restore_parameters, create_mode=create_mode, **kwargs) - self.rid = None - self.ts = None - self.etag = None - self.colls = colls - self.users = users - self.id = id - self.restore_parameters = restore_parameters - self.create_mode = create_mode - - -class SqlDatabaseGetResults(ARMResourceProperties): - """An Azure Cosmos DB SQL database. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: - :vartype resource: ~azure.mgmt.cosmosdb.models.SqlDatabaseGetPropertiesResource - :ivar options: - :vartype options: ~azure.mgmt.cosmosdb.models.SqlDatabaseGetPropertiesOptions - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "SqlDatabaseGetPropertiesResource"}, - "options": {"key": "properties.options", "type": "SqlDatabaseGetPropertiesOptions"}, - } - - def __init__( - self, - *, - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - resource: Optional["_models.SqlDatabaseGetPropertiesResource"] = None, - options: Optional["_models.SqlDatabaseGetPropertiesOptions"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: - :paramtype resource: ~azure.mgmt.cosmosdb.models.SqlDatabaseGetPropertiesResource - :keyword options: - :paramtype options: ~azure.mgmt.cosmosdb.models.SqlDatabaseGetPropertiesOptions - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - self.options = options - - -class SqlDatabaseListResult(_serialization.Model): - """The List operation response, that contains the SQL databases and their properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of SQL databases and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.SqlDatabaseGetResults] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[SqlDatabaseGetResults]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class SqlDedicatedGatewayRegionalServiceResource(RegionalServiceResource): # pylint: disable=name-too-long - """Resource for a regional service location. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar name: The regional service name. - :vartype name: str - :ivar location: The location name. - :vartype location: str - :ivar status: Describes the status of a service. Known values are: "Creating", "Running", - "Updating", "Deleting", "Error", and "Stopped". - :vartype status: str or ~azure.mgmt.cosmosdb.models.ServiceStatus - :ivar sql_dedicated_gateway_endpoint: The regional endpoint for SqlDedicatedGateway. - :vartype sql_dedicated_gateway_endpoint: str - """ - - _validation = { - "name": {"readonly": True}, - "location": {"readonly": True}, - "status": {"readonly": True}, - "sql_dedicated_gateway_endpoint": {"readonly": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "status": {"key": "status", "type": "str"}, - "sql_dedicated_gateway_endpoint": {"key": "sqlDedicatedGatewayEndpoint", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.sql_dedicated_gateway_endpoint = None - - -class SqlDedicatedGatewayServiceResource(_serialization.Model): - """Describes the service response property for SqlDedicatedGateway. - - :ivar properties: Properties for SqlDedicatedGatewayServiceResource. - :vartype properties: ~azure.mgmt.cosmosdb.models.SqlDedicatedGatewayServiceResourceProperties - """ - - _attribute_map = { - "properties": {"key": "properties", "type": "SqlDedicatedGatewayServiceResourceProperties"}, - } - - def __init__( - self, *, properties: Optional["_models.SqlDedicatedGatewayServiceResourceProperties"] = None, **kwargs: Any - ) -> None: - """ - :keyword properties: Properties for SqlDedicatedGatewayServiceResource. - :paramtype properties: ~azure.mgmt.cosmosdb.models.SqlDedicatedGatewayServiceResourceProperties - """ - super().__init__(**kwargs) - self.properties = properties - - -class SqlDedicatedGatewayServiceResourceCreateUpdateProperties( - ServiceResourceCreateUpdateProperties -): # pylint: disable=name-too-long - """Properties for Create or Update request for SqlDedicatedGatewayServiceResource. - - All required parameters must be populated in order to send to server. - - :ivar instance_size: Instance type for the service. Known values are: "Cosmos.D4s", - "Cosmos.D8s", and "Cosmos.D16s". - :vartype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize - :ivar instance_count: Instance count for the service. - :vartype instance_count: int - :ivar service_type: ServiceType for the service. Required. Known values are: - "SqlDedicatedGateway", "DataTransfer", "GraphAPICompute", and "MaterializedViewsBuilder". - :vartype service_type: str or ~azure.mgmt.cosmosdb.models.ServiceType - :ivar dedicated_gateway_type: DedicatedGatewayType for the service. Known values are: - "IntegratedCache" and "DistributedQuery". - :vartype dedicated_gateway_type: str or ~azure.mgmt.cosmosdb.models.DedicatedGatewayType - """ - - _validation = { - "instance_count": {"minimum": 0}, - "service_type": {"required": True}, - } - - _attribute_map = { - "instance_size": {"key": "instanceSize", "type": "str"}, - "instance_count": {"key": "instanceCount", "type": "int"}, - "service_type": {"key": "serviceType", "type": "str"}, - "dedicated_gateway_type": {"key": "dedicatedGatewayType", "type": "str"}, - } - - def __init__( - self, - *, - instance_size: Optional[Union[str, "_models.ServiceSize"]] = None, - instance_count: Optional[int] = None, - dedicated_gateway_type: Optional[Union[str, "_models.DedicatedGatewayType"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword instance_size: Instance type for the service. Known values are: "Cosmos.D4s", - "Cosmos.D8s", and "Cosmos.D16s". - :paramtype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize - :keyword instance_count: Instance count for the service. - :paramtype instance_count: int - :keyword dedicated_gateway_type: DedicatedGatewayType for the service. Known values are: - "IntegratedCache" and "DistributedQuery". - :paramtype dedicated_gateway_type: str or ~azure.mgmt.cosmosdb.models.DedicatedGatewayType - """ - super().__init__(instance_size=instance_size, instance_count=instance_count, **kwargs) - self.service_type: str = "SqlDedicatedGateway" - self.dedicated_gateway_type = dedicated_gateway_type - - -class SqlDedicatedGatewayServiceResourceProperties(ServiceResourceProperties): # pylint: disable=name-too-long - """Properties for SqlDedicatedGatewayServiceResource. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar additional_properties: Unmatched properties from the message are deserialized to this - collection. - :vartype additional_properties: dict[str, any] - :ivar creation_time: Time of the last state change (ISO-8601 format). - :vartype creation_time: ~datetime.datetime - :ivar instance_size: Instance type for the service. Known values are: "Cosmos.D4s", - "Cosmos.D8s", and "Cosmos.D16s". - :vartype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize - :ivar instance_count: Instance count for the service. - :vartype instance_count: int - :ivar service_type: ServiceType for the service. Required. Known values are: - "SqlDedicatedGateway", "DataTransfer", "GraphAPICompute", and "MaterializedViewsBuilder". - :vartype service_type: str or ~azure.mgmt.cosmosdb.models.ServiceType - :ivar status: Describes the status of a service. Known values are: "Creating", "Running", - "Updating", "Deleting", "Error", and "Stopped". - :vartype status: str or ~azure.mgmt.cosmosdb.models.ServiceStatus - :ivar sql_dedicated_gateway_endpoint: SqlDedicatedGateway endpoint for the service. - :vartype sql_dedicated_gateway_endpoint: str - :ivar dedicated_gateway_type: DedicatedGatewayType for the service. Known values are: - "IntegratedCache" and "DistributedQuery". - :vartype dedicated_gateway_type: str or ~azure.mgmt.cosmosdb.models.DedicatedGatewayType - :ivar locations: An array that contains all of the locations for the service. - :vartype locations: - list[~azure.mgmt.cosmosdb.models.SqlDedicatedGatewayRegionalServiceResource] - """ - - _validation = { - "creation_time": {"readonly": True}, - "instance_count": {"minimum": 0}, - "service_type": {"required": True}, - "status": {"readonly": True}, - "locations": {"readonly": True}, - } - - _attribute_map = { - "additional_properties": {"key": "", "type": "{object}"}, - "creation_time": {"key": "creationTime", "type": "iso-8601"}, - "instance_size": {"key": "instanceSize", "type": "str"}, - "instance_count": {"key": "instanceCount", "type": "int"}, - "service_type": {"key": "serviceType", "type": "str"}, - "status": {"key": "status", "type": "str"}, - "sql_dedicated_gateway_endpoint": {"key": "sqlDedicatedGatewayEndpoint", "type": "str"}, - "dedicated_gateway_type": {"key": "dedicatedGatewayType", "type": "str"}, - "locations": {"key": "locations", "type": "[SqlDedicatedGatewayRegionalServiceResource]"}, - } - - def __init__( - self, - *, - additional_properties: Optional[Dict[str, Any]] = None, - instance_size: Optional[Union[str, "_models.ServiceSize"]] = None, - instance_count: Optional[int] = None, - sql_dedicated_gateway_endpoint: Optional[str] = None, - dedicated_gateway_type: Optional[Union[str, "_models.DedicatedGatewayType"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword additional_properties: Unmatched properties from the message are deserialized to this - collection. - :paramtype additional_properties: dict[str, any] - :keyword instance_size: Instance type for the service. Known values are: "Cosmos.D4s", - "Cosmos.D8s", and "Cosmos.D16s". - :paramtype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize - :keyword instance_count: Instance count for the service. - :paramtype instance_count: int - :keyword sql_dedicated_gateway_endpoint: SqlDedicatedGateway endpoint for the service. - :paramtype sql_dedicated_gateway_endpoint: str - :keyword dedicated_gateway_type: DedicatedGatewayType for the service. Known values are: - "IntegratedCache" and "DistributedQuery". - :paramtype dedicated_gateway_type: str or ~azure.mgmt.cosmosdb.models.DedicatedGatewayType - """ - super().__init__( - additional_properties=additional_properties, - instance_size=instance_size, - instance_count=instance_count, - **kwargs - ) - self.service_type: str = "SqlDedicatedGateway" - self.sql_dedicated_gateway_endpoint = sql_dedicated_gateway_endpoint - self.dedicated_gateway_type = dedicated_gateway_type - self.locations = None - - -class SqlRoleAssignmentCreateUpdateParameters(_serialization.Model): - """Parameters to create and update an Azure Cosmos DB SQL Role Assignment. - - :ivar role_definition_id: The unique identifier for the associated Role Definition. - :vartype role_definition_id: str - :ivar scope: The data plane resource path for which access is being granted through this Role - Assignment. - :vartype scope: str - :ivar principal_id: The unique identifier for the associated AAD principal in the AAD graph to - which access is being granted through this Role Assignment. Tenant ID for the principal is - inferred using the tenant associated with the subscription. - :vartype principal_id: str - """ - - _attribute_map = { - "role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"}, - "scope": {"key": "properties.scope", "type": "str"}, - "principal_id": {"key": "properties.principalId", "type": "str"}, - } - - def __init__( - self, - *, - role_definition_id: Optional[str] = None, - scope: Optional[str] = None, - principal_id: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword role_definition_id: The unique identifier for the associated Role Definition. - :paramtype role_definition_id: str - :keyword scope: The data plane resource path for which access is being granted through this - Role Assignment. - :paramtype scope: str - :keyword principal_id: The unique identifier for the associated AAD principal in the AAD graph - to which access is being granted through this Role Assignment. Tenant ID for the principal is - inferred using the tenant associated with the subscription. - :paramtype principal_id: str - """ - super().__init__(**kwargs) - self.role_definition_id = role_definition_id - self.scope = scope - self.principal_id = principal_id - - -class SqlRoleAssignmentGetResults(ARMProxyResource): - """An Azure Cosmos DB Role Assignment. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the database account. - :vartype id: str - :ivar name: The name of the database account. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar role_definition_id: The unique identifier for the associated Role Definition. - :vartype role_definition_id: str - :ivar scope: The data plane resource path for which access is being granted through this Role - Assignment. - :vartype scope: str - :ivar principal_id: The unique identifier for the associated AAD principal in the AAD graph to - which access is being granted through this Role Assignment. Tenant ID for the principal is - inferred using the tenant associated with the subscription. - :vartype principal_id: str - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"}, - "scope": {"key": "properties.scope", "type": "str"}, - "principal_id": {"key": "properties.principalId", "type": "str"}, - } - - def __init__( - self, - *, - role_definition_id: Optional[str] = None, - scope: Optional[str] = None, - principal_id: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword role_definition_id: The unique identifier for the associated Role Definition. - :paramtype role_definition_id: str - :keyword scope: The data plane resource path for which access is being granted through this - Role Assignment. - :paramtype scope: str - :keyword principal_id: The unique identifier for the associated AAD principal in the AAD graph - to which access is being granted through this Role Assignment. Tenant ID for the principal is - inferred using the tenant associated with the subscription. - :paramtype principal_id: str - """ - super().__init__(**kwargs) - self.role_definition_id = role_definition_id - self.scope = scope - self.principal_id = principal_id - - -class SqlRoleAssignmentListResult(_serialization.Model): - """The relevant Role Assignments. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of Role Assignments and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.SqlRoleAssignmentGetResults] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[SqlRoleAssignmentGetResults]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class SqlRoleDefinitionCreateUpdateParameters(_serialization.Model): - """Parameters to create and update an Azure Cosmos DB SQL Role Definition. - - :ivar role_name: A user-friendly name for the Role Definition. Must be unique for the database - account. - :vartype role_name: str - :ivar type: Indicates whether the Role Definition was built-in or user created. Known values - are: "BuiltInRole" and "CustomRole". - :vartype type: str or ~azure.mgmt.cosmosdb.models.RoleDefinitionType - :ivar assignable_scopes: A set of fully qualified Scopes at or below which Role Assignments may - be created using this Role Definition. This will allow application of this Role Definition on - the entire database account or any underlying Database / Collection. Must have at least one - element. Scopes higher than Database account are not enforceable as assignable Scopes. Note - that resources referenced in assignable Scopes need not exist. - :vartype assignable_scopes: list[str] - :ivar permissions: The set of operations allowed through this Role Definition. - :vartype permissions: list[~azure.mgmt.cosmosdb.models.Permission] - """ - - _attribute_map = { - "role_name": {"key": "properties.roleName", "type": "str"}, - "type": {"key": "properties.type", "type": "str"}, - "assignable_scopes": {"key": "properties.assignableScopes", "type": "[str]"}, - "permissions": {"key": "properties.permissions", "type": "[Permission]"}, - } - - def __init__( - self, - *, - role_name: Optional[str] = None, - type: Optional[Union[str, "_models.RoleDefinitionType"]] = None, - assignable_scopes: Optional[List[str]] = None, - permissions: Optional[List["_models.Permission"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword role_name: A user-friendly name for the Role Definition. Must be unique for the - database account. - :paramtype role_name: str - :keyword type: Indicates whether the Role Definition was built-in or user created. Known values - are: "BuiltInRole" and "CustomRole". - :paramtype type: str or ~azure.mgmt.cosmosdb.models.RoleDefinitionType - :keyword assignable_scopes: A set of fully qualified Scopes at or below which Role Assignments - may be created using this Role Definition. This will allow application of this Role Definition - on the entire database account or any underlying Database / Collection. Must have at least one - element. Scopes higher than Database account are not enforceable as assignable Scopes. Note - that resources referenced in assignable Scopes need not exist. - :paramtype assignable_scopes: list[str] - :keyword permissions: The set of operations allowed through this Role Definition. - :paramtype permissions: list[~azure.mgmt.cosmosdb.models.Permission] - """ - super().__init__(**kwargs) - self.role_name = role_name - self.type = type - self.assignable_scopes = assignable_scopes - self.permissions = permissions - - -class SqlRoleDefinitionGetResults(ARMProxyResource): - """An Azure Cosmos DB SQL Role Definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the database account. - :vartype id: str - :ivar name: The name of the database account. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar role_name: A user-friendly name for the Role Definition. Must be unique for the database - account. - :vartype role_name: str - :ivar type_properties_type: Indicates whether the Role Definition was built-in or user created. - Known values are: "BuiltInRole" and "CustomRole". - :vartype type_properties_type: str or ~azure.mgmt.cosmosdb.models.RoleDefinitionType - :ivar assignable_scopes: A set of fully qualified Scopes at or below which Role Assignments may - be created using this Role Definition. This will allow application of this Role Definition on - the entire database account or any underlying Database / Collection. Must have at least one - element. Scopes higher than Database account are not enforceable as assignable Scopes. Note - that resources referenced in assignable Scopes need not exist. - :vartype assignable_scopes: list[str] - :ivar permissions: The set of operations allowed through this Role Definition. - :vartype permissions: list[~azure.mgmt.cosmosdb.models.Permission] - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "role_name": {"key": "properties.roleName", "type": "str"}, - "type_properties_type": {"key": "properties.type", "type": "str"}, - "assignable_scopes": {"key": "properties.assignableScopes", "type": "[str]"}, - "permissions": {"key": "properties.permissions", "type": "[Permission]"}, - } - - def __init__( - self, - *, - role_name: Optional[str] = None, - type_properties_type: Optional[Union[str, "_models.RoleDefinitionType"]] = None, - assignable_scopes: Optional[List[str]] = None, - permissions: Optional[List["_models.Permission"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword role_name: A user-friendly name for the Role Definition. Must be unique for the - database account. - :paramtype role_name: str - :keyword type_properties_type: Indicates whether the Role Definition was built-in or user - created. Known values are: "BuiltInRole" and "CustomRole". - :paramtype type_properties_type: str or ~azure.mgmt.cosmosdb.models.RoleDefinitionType - :keyword assignable_scopes: A set of fully qualified Scopes at or below which Role Assignments - may be created using this Role Definition. This will allow application of this Role Definition - on the entire database account or any underlying Database / Collection. Must have at least one - element. Scopes higher than Database account are not enforceable as assignable Scopes. Note - that resources referenced in assignable Scopes need not exist. - :paramtype assignable_scopes: list[str] - :keyword permissions: The set of operations allowed through this Role Definition. - :paramtype permissions: list[~azure.mgmt.cosmosdb.models.Permission] - """ - super().__init__(**kwargs) - self.role_name = role_name - self.type_properties_type = type_properties_type - self.assignable_scopes = assignable_scopes - self.permissions = permissions - - -class SqlRoleDefinitionListResult(_serialization.Model): - """The relevant Role Definitions. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of Role Definitions and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.SqlRoleDefinitionGetResults] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[SqlRoleDefinitionGetResults]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class SqlStoredProcedureCreateUpdateParameters(ARMResourceProperties): - """Parameters to create and update Cosmos DB storedProcedure. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: The standard JSON format of a storedProcedure. Required. - :vartype resource: ~azure.mgmt.cosmosdb.models.SqlStoredProcedureResource - :ivar options: A key-value pair of options to be applied for the request. This corresponds to - the headers sent with the request. - :vartype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "resource": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "SqlStoredProcedureResource"}, - "options": {"key": "properties.options", "type": "CreateUpdateOptions"}, - } - - def __init__( - self, - *, - resource: "_models.SqlStoredProcedureResource", - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - options: Optional["_models.CreateUpdateOptions"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: The standard JSON format of a storedProcedure. Required. - :paramtype resource: ~azure.mgmt.cosmosdb.models.SqlStoredProcedureResource - :keyword options: A key-value pair of options to be applied for the request. This corresponds - to the headers sent with the request. - :paramtype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - self.options = options - - -class SqlStoredProcedureResource(_serialization.Model): - """Cosmos DB SQL storedProcedure resource object. - - All required parameters must be populated in order to send to server. - - :ivar id: Name of the Cosmos DB SQL storedProcedure. Required. - :vartype id: str - :ivar body: Body of the Stored Procedure. - :vartype body: str - """ - - _validation = { - "id": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "body": {"key": "body", "type": "str"}, - } - - def __init__( - self, *, id: str, body: Optional[str] = None, **kwargs: Any # pylint: disable=redefined-builtin - ) -> None: - """ - :keyword id: Name of the Cosmos DB SQL storedProcedure. Required. - :paramtype id: str - :keyword body: Body of the Stored Procedure. - :paramtype body: str - """ - super().__init__(**kwargs) - self.id = id - self.body = body - - -class SqlStoredProcedureGetPropertiesResource(SqlStoredProcedureResource, ExtendedResourceProperties): - """SqlStoredProcedureGetPropertiesResource. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar rid: A system generated property. A unique identifier. - :vartype rid: str - :ivar ts: A system generated property that denotes the last updated timestamp of the resource. - :vartype ts: float - :ivar etag: A system generated property representing the resource etag required for optimistic - concurrency control. - :vartype etag: str - :ivar id: Name of the Cosmos DB SQL storedProcedure. Required. - :vartype id: str - :ivar body: Body of the Stored Procedure. - :vartype body: str - """ - - _validation = { - "rid": {"readonly": True}, - "ts": {"readonly": True}, - "etag": {"readonly": True}, - "id": {"required": True}, - } - - _attribute_map = { - "rid": {"key": "_rid", "type": "str"}, - "ts": {"key": "_ts", "type": "float"}, - "etag": {"key": "_etag", "type": "str"}, - "id": {"key": "id", "type": "str"}, - "body": {"key": "body", "type": "str"}, - } - - def __init__( - self, *, id: str, body: Optional[str] = None, **kwargs: Any # pylint: disable=redefined-builtin - ) -> None: - """ - :keyword id: Name of the Cosmos DB SQL storedProcedure. Required. - :paramtype id: str - :keyword body: Body of the Stored Procedure. - :paramtype body: str - """ - super().__init__(id=id, body=body, **kwargs) - self.rid = None - self.ts = None - self.etag = None - self.id = id - self.body = body - - -class SqlStoredProcedureGetResults(ARMResourceProperties): - """An Azure Cosmos DB storedProcedure. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: - :vartype resource: ~azure.mgmt.cosmosdb.models.SqlStoredProcedureGetPropertiesResource - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "SqlStoredProcedureGetPropertiesResource"}, - } - - def __init__( - self, - *, - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - resource: Optional["_models.SqlStoredProcedureGetPropertiesResource"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: - :paramtype resource: ~azure.mgmt.cosmosdb.models.SqlStoredProcedureGetPropertiesResource - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - - -class SqlStoredProcedureListResult(_serialization.Model): - """The List operation response, that contains the storedProcedures and their properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of storedProcedures and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.SqlStoredProcedureGetResults] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[SqlStoredProcedureGetResults]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class SqlTriggerCreateUpdateParameters(ARMResourceProperties): - """Parameters to create and update Cosmos DB trigger. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: The standard JSON format of a trigger. Required. - :vartype resource: ~azure.mgmt.cosmosdb.models.SqlTriggerResource - :ivar options: A key-value pair of options to be applied for the request. This corresponds to - the headers sent with the request. - :vartype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "resource": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "SqlTriggerResource"}, - "options": {"key": "properties.options", "type": "CreateUpdateOptions"}, - } - - def __init__( - self, - *, - resource: "_models.SqlTriggerResource", - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - options: Optional["_models.CreateUpdateOptions"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: The standard JSON format of a trigger. Required. - :paramtype resource: ~azure.mgmt.cosmosdb.models.SqlTriggerResource - :keyword options: A key-value pair of options to be applied for the request. This corresponds - to the headers sent with the request. - :paramtype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - self.options = options - - -class SqlTriggerResource(_serialization.Model): - """Cosmos DB SQL trigger resource object. - - All required parameters must be populated in order to send to server. - - :ivar id: Name of the Cosmos DB SQL trigger. Required. - :vartype id: str - :ivar body: Body of the Trigger. - :vartype body: str - :ivar trigger_type: Type of the Trigger. Known values are: "Pre" and "Post". - :vartype trigger_type: str or ~azure.mgmt.cosmosdb.models.TriggerType - :ivar trigger_operation: The operation the trigger is associated with. Known values are: "All", - "Create", "Update", "Delete", and "Replace". - :vartype trigger_operation: str or ~azure.mgmt.cosmosdb.models.TriggerOperation - """ - - _validation = { - "id": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "body": {"key": "body", "type": "str"}, - "trigger_type": {"key": "triggerType", "type": "str"}, - "trigger_operation": {"key": "triggerOperation", "type": "str"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - body: Optional[str] = None, - trigger_type: Optional[Union[str, "_models.TriggerType"]] = None, - trigger_operation: Optional[Union[str, "_models.TriggerOperation"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: Name of the Cosmos DB SQL trigger. Required. - :paramtype id: str - :keyword body: Body of the Trigger. - :paramtype body: str - :keyword trigger_type: Type of the Trigger. Known values are: "Pre" and "Post". - :paramtype trigger_type: str or ~azure.mgmt.cosmosdb.models.TriggerType - :keyword trigger_operation: The operation the trigger is associated with. Known values are: - "All", "Create", "Update", "Delete", and "Replace". - :paramtype trigger_operation: str or ~azure.mgmt.cosmosdb.models.TriggerOperation - """ - super().__init__(**kwargs) - self.id = id - self.body = body - self.trigger_type = trigger_type - self.trigger_operation = trigger_operation - - -class SqlTriggerGetPropertiesResource(SqlTriggerResource, ExtendedResourceProperties): - """SqlTriggerGetPropertiesResource. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar rid: A system generated property. A unique identifier. - :vartype rid: str - :ivar ts: A system generated property that denotes the last updated timestamp of the resource. - :vartype ts: float - :ivar etag: A system generated property representing the resource etag required for optimistic - concurrency control. - :vartype etag: str - :ivar id: Name of the Cosmos DB SQL trigger. Required. - :vartype id: str - :ivar body: Body of the Trigger. - :vartype body: str - :ivar trigger_type: Type of the Trigger. Known values are: "Pre" and "Post". - :vartype trigger_type: str or ~azure.mgmt.cosmosdb.models.TriggerType - :ivar trigger_operation: The operation the trigger is associated with. Known values are: "All", - "Create", "Update", "Delete", and "Replace". - :vartype trigger_operation: str or ~azure.mgmt.cosmosdb.models.TriggerOperation - """ - - _validation = { - "rid": {"readonly": True}, - "ts": {"readonly": True}, - "etag": {"readonly": True}, - "id": {"required": True}, - } - - _attribute_map = { - "rid": {"key": "_rid", "type": "str"}, - "ts": {"key": "_ts", "type": "float"}, - "etag": {"key": "_etag", "type": "str"}, - "id": {"key": "id", "type": "str"}, - "body": {"key": "body", "type": "str"}, - "trigger_type": {"key": "triggerType", "type": "str"}, - "trigger_operation": {"key": "triggerOperation", "type": "str"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - body: Optional[str] = None, - trigger_type: Optional[Union[str, "_models.TriggerType"]] = None, - trigger_operation: Optional[Union[str, "_models.TriggerOperation"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: Name of the Cosmos DB SQL trigger. Required. - :paramtype id: str - :keyword body: Body of the Trigger. - :paramtype body: str - :keyword trigger_type: Type of the Trigger. Known values are: "Pre" and "Post". - :paramtype trigger_type: str or ~azure.mgmt.cosmosdb.models.TriggerType - :keyword trigger_operation: The operation the trigger is associated with. Known values are: - "All", "Create", "Update", "Delete", and "Replace". - :paramtype trigger_operation: str or ~azure.mgmt.cosmosdb.models.TriggerOperation - """ - super().__init__(id=id, body=body, trigger_type=trigger_type, trigger_operation=trigger_operation, **kwargs) - self.rid = None - self.ts = None - self.etag = None - self.id = id - self.body = body - self.trigger_type = trigger_type - self.trigger_operation = trigger_operation - - -class SqlTriggerGetResults(ARMResourceProperties): - """An Azure Cosmos DB trigger. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: - :vartype resource: ~azure.mgmt.cosmosdb.models.SqlTriggerGetPropertiesResource - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "SqlTriggerGetPropertiesResource"}, - } - - def __init__( - self, - *, - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - resource: Optional["_models.SqlTriggerGetPropertiesResource"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: - :paramtype resource: ~azure.mgmt.cosmosdb.models.SqlTriggerGetPropertiesResource - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - - -class SqlTriggerListResult(_serialization.Model): - """The List operation response, that contains the triggers and their properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of triggers and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.SqlTriggerGetResults] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[SqlTriggerGetResults]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class SqlUserDefinedFunctionCreateUpdateParameters(ARMResourceProperties): # pylint: disable=name-too-long - """Parameters to create and update Cosmos DB userDefinedFunction. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: The standard JSON format of a userDefinedFunction. Required. - :vartype resource: ~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionResource - :ivar options: A key-value pair of options to be applied for the request. This corresponds to - the headers sent with the request. - :vartype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "resource": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "SqlUserDefinedFunctionResource"}, - "options": {"key": "properties.options", "type": "CreateUpdateOptions"}, - } - - def __init__( - self, - *, - resource: "_models.SqlUserDefinedFunctionResource", - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - options: Optional["_models.CreateUpdateOptions"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: The standard JSON format of a userDefinedFunction. Required. - :paramtype resource: ~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionResource - :keyword options: A key-value pair of options to be applied for the request. This corresponds - to the headers sent with the request. - :paramtype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - self.options = options - - -class SqlUserDefinedFunctionResource(_serialization.Model): - """Cosmos DB SQL userDefinedFunction resource object. - - All required parameters must be populated in order to send to server. - - :ivar id: Name of the Cosmos DB SQL userDefinedFunction. Required. - :vartype id: str - :ivar body: Body of the User Defined Function. - :vartype body: str - """ - - _validation = { - "id": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "body": {"key": "body", "type": "str"}, - } - - def __init__( - self, *, id: str, body: Optional[str] = None, **kwargs: Any # pylint: disable=redefined-builtin - ) -> None: - """ - :keyword id: Name of the Cosmos DB SQL userDefinedFunction. Required. - :paramtype id: str - :keyword body: Body of the User Defined Function. - :paramtype body: str - """ - super().__init__(**kwargs) - self.id = id - self.body = body - - -class SqlUserDefinedFunctionGetPropertiesResource( - SqlUserDefinedFunctionResource, ExtendedResourceProperties -): # pylint: disable=name-too-long - """SqlUserDefinedFunctionGetPropertiesResource. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar rid: A system generated property. A unique identifier. - :vartype rid: str - :ivar ts: A system generated property that denotes the last updated timestamp of the resource. - :vartype ts: float - :ivar etag: A system generated property representing the resource etag required for optimistic - concurrency control. - :vartype etag: str - :ivar id: Name of the Cosmos DB SQL userDefinedFunction. Required. - :vartype id: str - :ivar body: Body of the User Defined Function. - :vartype body: str - """ - - _validation = { - "rid": {"readonly": True}, - "ts": {"readonly": True}, - "etag": {"readonly": True}, - "id": {"required": True}, - } - - _attribute_map = { - "rid": {"key": "_rid", "type": "str"}, - "ts": {"key": "_ts", "type": "float"}, - "etag": {"key": "_etag", "type": "str"}, - "id": {"key": "id", "type": "str"}, - "body": {"key": "body", "type": "str"}, - } - - def __init__( - self, *, id: str, body: Optional[str] = None, **kwargs: Any # pylint: disable=redefined-builtin - ) -> None: - """ - :keyword id: Name of the Cosmos DB SQL userDefinedFunction. Required. - :paramtype id: str - :keyword body: Body of the User Defined Function. - :paramtype body: str - """ - super().__init__(id=id, body=body, **kwargs) - self.rid = None - self.ts = None - self.etag = None - self.id = id - self.body = body - - -class SqlUserDefinedFunctionGetResults(ARMResourceProperties): - """An Azure Cosmos DB userDefinedFunction. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: - :vartype resource: ~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionGetPropertiesResource - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "SqlUserDefinedFunctionGetPropertiesResource"}, - } - - def __init__( - self, - *, - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - resource: Optional["_models.SqlUserDefinedFunctionGetPropertiesResource"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: - :paramtype resource: ~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionGetPropertiesResource - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - - -class SqlUserDefinedFunctionListResult(_serialization.Model): - """The List operation response, that contains the userDefinedFunctions and their properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of userDefinedFunctions and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionGetResults] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[SqlUserDefinedFunctionGetResults]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class SystemData(_serialization.Model): - """Metadata pertaining to creation and last modification of the resource. - - :ivar created_by: The identity that created the resource. - :vartype created_by: str - :ivar created_by_type: The type of identity that created the resource. Known values are: - "User", "Application", "ManagedIdentity", and "Key". - :vartype created_by_type: str or ~azure.mgmt.cosmosdb.models.CreatedByType - :ivar created_at: The timestamp of resource creation (UTC). - :vartype created_at: ~datetime.datetime - :ivar last_modified_by: The identity that last modified the resource. - :vartype last_modified_by: str - :ivar last_modified_by_type: The type of identity that last modified the resource. Known values - are: "User", "Application", "ManagedIdentity", and "Key". - :vartype last_modified_by_type: str or ~azure.mgmt.cosmosdb.models.CreatedByType - :ivar last_modified_at: The timestamp of resource last modification (UTC). - :vartype last_modified_at: ~datetime.datetime - """ - - _attribute_map = { - "created_by": {"key": "createdBy", "type": "str"}, - "created_by_type": {"key": "createdByType", "type": "str"}, - "created_at": {"key": "createdAt", "type": "iso-8601"}, - "last_modified_by": {"key": "lastModifiedBy", "type": "str"}, - "last_modified_by_type": {"key": "lastModifiedByType", "type": "str"}, - "last_modified_at": {"key": "lastModifiedAt", "type": "iso-8601"}, - } - - def __init__( - self, - *, - created_by: Optional[str] = None, - created_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, - created_at: Optional[datetime.datetime] = None, - last_modified_by: Optional[str] = None, - last_modified_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, - last_modified_at: Optional[datetime.datetime] = None, - **kwargs: Any - ) -> None: - """ - :keyword created_by: The identity that created the resource. - :paramtype created_by: str - :keyword created_by_type: The type of identity that created the resource. Known values are: - "User", "Application", "ManagedIdentity", and "Key". - :paramtype created_by_type: str or ~azure.mgmt.cosmosdb.models.CreatedByType - :keyword created_at: The timestamp of resource creation (UTC). - :paramtype created_at: ~datetime.datetime - :keyword last_modified_by: The identity that last modified the resource. - :paramtype last_modified_by: str - :keyword last_modified_by_type: The type of identity that last modified the resource. Known - values are: "User", "Application", "ManagedIdentity", and "Key". - :paramtype last_modified_by_type: str or ~azure.mgmt.cosmosdb.models.CreatedByType - :keyword last_modified_at: The timestamp of resource last modification (UTC). - :paramtype last_modified_at: ~datetime.datetime - """ - super().__init__(**kwargs) - self.created_by = created_by - self.created_by_type = created_by_type - self.created_at = created_at - self.last_modified_by = last_modified_by - self.last_modified_by_type = last_modified_by_type - self.last_modified_at = last_modified_at - - -class TableCreateUpdateParameters(ARMResourceProperties): - """Parameters to create and update Cosmos DB Table. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: The standard JSON format of a Table. Required. - :vartype resource: ~azure.mgmt.cosmosdb.models.TableResource - :ivar options: A key-value pair of options to be applied for the request. This corresponds to - the headers sent with the request. - :vartype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "resource": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "TableResource"}, - "options": {"key": "properties.options", "type": "CreateUpdateOptions"}, - } - - def __init__( - self, - *, - resource: "_models.TableResource", - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - options: Optional["_models.CreateUpdateOptions"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: The standard JSON format of a Table. Required. - :paramtype resource: ~azure.mgmt.cosmosdb.models.TableResource - :keyword options: A key-value pair of options to be applied for the request. This corresponds - to the headers sent with the request. - :paramtype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - self.options = options - - -class TableGetPropertiesOptions(OptionsResource): - """TableGetPropertiesOptions. - - :ivar throughput: Value of the Cosmos DB resource throughput or autoscaleSettings. Use the - ThroughputSetting resource when retrieving offer details. - :vartype throughput: int - :ivar autoscale_settings: Specifies the Autoscale settings. - :vartype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettings - """ - - -class TableResource(_serialization.Model): - """Cosmos DB table resource object. - - All required parameters must be populated in order to send to server. - - :ivar id: Name of the Cosmos DB table. Required. - :vartype id: str - :ivar restore_parameters: Parameters to indicate the information about the restore. - :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" - and "Restore". - :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - """ - - _validation = { - "id": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, - "create_mode": {"key": "createMode", "type": "str"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, - create_mode: Union[str, "_models.CreateMode"] = "Default", - **kwargs: Any - ) -> None: - """ - :keyword id: Name of the Cosmos DB table. Required. - :paramtype id: str - :keyword restore_parameters: Parameters to indicate the information about the restore. - :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: - "Default" and "Restore". - :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - """ - super().__init__(**kwargs) - self.id = id - self.restore_parameters = restore_parameters - self.create_mode = create_mode - - -class TableGetPropertiesResource(TableResource, ExtendedResourceProperties): - """TableGetPropertiesResource. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar rid: A system generated property. A unique identifier. - :vartype rid: str - :ivar ts: A system generated property that denotes the last updated timestamp of the resource. - :vartype ts: float - :ivar etag: A system generated property representing the resource etag required for optimistic - concurrency control. - :vartype etag: str - :ivar id: Name of the Cosmos DB table. Required. - :vartype id: str - :ivar restore_parameters: Parameters to indicate the information about the restore. - :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" - and "Restore". - :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - """ - - _validation = { - "rid": {"readonly": True}, - "ts": {"readonly": True}, - "etag": {"readonly": True}, - "id": {"required": True}, - } - - _attribute_map = { - "rid": {"key": "_rid", "type": "str"}, - "ts": {"key": "_ts", "type": "float"}, - "etag": {"key": "_etag", "type": "str"}, - "id": {"key": "id", "type": "str"}, - "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, - "create_mode": {"key": "createMode", "type": "str"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, - create_mode: Union[str, "_models.CreateMode"] = "Default", - **kwargs: Any - ) -> None: - """ - :keyword id: Name of the Cosmos DB table. Required. - :paramtype id: str - :keyword restore_parameters: Parameters to indicate the information about the restore. - :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters - :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: - "Default" and "Restore". - :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode - """ - super().__init__(id=id, restore_parameters=restore_parameters, create_mode=create_mode, **kwargs) - self.rid = None - self.ts = None - self.etag = None - self.id = id - self.restore_parameters = restore_parameters - self.create_mode = create_mode - - -class TableGetResults(ARMResourceProperties): - """An Azure Cosmos DB Table. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: - :vartype resource: ~azure.mgmt.cosmosdb.models.TableGetPropertiesResource - :ivar options: - :vartype options: ~azure.mgmt.cosmosdb.models.TableGetPropertiesOptions - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "TableGetPropertiesResource"}, - "options": {"key": "properties.options", "type": "TableGetPropertiesOptions"}, - } - - def __init__( - self, - *, - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - resource: Optional["_models.TableGetPropertiesResource"] = None, - options: Optional["_models.TableGetPropertiesOptions"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: - :paramtype resource: ~azure.mgmt.cosmosdb.models.TableGetPropertiesResource - :keyword options: - :paramtype options: ~azure.mgmt.cosmosdb.models.TableGetPropertiesOptions - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - self.options = options - - -class TableListResult(_serialization.Model): - """The List operation response, that contains the Table and their properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of Table and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.TableGetResults] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[TableGetResults]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class ThroughputPolicyResource(_serialization.Model): - """Cosmos DB resource throughput policy. - - :ivar is_enabled: Determines whether the ThroughputPolicy is active or not. - :vartype is_enabled: bool - :ivar increment_percent: Represents the percentage by which throughput can increase every time - throughput policy kicks in. - :vartype increment_percent: int - """ - - _attribute_map = { - "is_enabled": {"key": "isEnabled", "type": "bool"}, - "increment_percent": {"key": "incrementPercent", "type": "int"}, - } - - def __init__( - self, *, is_enabled: Optional[bool] = None, increment_percent: Optional[int] = None, **kwargs: Any - ) -> None: - """ - :keyword is_enabled: Determines whether the ThroughputPolicy is active or not. - :paramtype is_enabled: bool - :keyword increment_percent: Represents the percentage by which throughput can increase every - time throughput policy kicks in. - :paramtype increment_percent: int - """ - super().__init__(**kwargs) - self.is_enabled = is_enabled - self.increment_percent = increment_percent - - -class ThroughputPoolAccountCreateParameters(_serialization.Model): - """Parameters for creating a Azure Cosmos DB throughput pool account. - - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar account_resource_identifier: The resource identifier of global database account in the - throughputPool. - :vartype account_resource_identifier: str - :ivar account_location: The location of global database account in the throughputPool. - :vartype account_location: str - """ - - _attribute_map = { - "tags": {"key": "tags", "type": "{str}"}, - "account_resource_identifier": {"key": "properties.accountResourceIdentifier", "type": "str"}, - "account_location": {"key": "properties.accountLocation", "type": "str"}, - } - - def __init__( - self, - *, - tags: Optional[Dict[str, str]] = None, - account_resource_identifier: Optional[str] = None, - account_location: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword account_resource_identifier: The resource identifier of global database account in the - throughputPool. - :paramtype account_resource_identifier: str - :keyword account_location: The location of global database account in the throughputPool. - :paramtype account_location: str - """ - super().__init__(**kwargs) - self.tags = tags - self.account_resource_identifier = account_resource_identifier - self.account_location = account_location - - -class ThroughputPoolAccountResource(ProxyResource): - """An Azure Cosmos DB Throughputpool Account. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Fully qualified resource ID for the resource. E.g. - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or - "Microsoft.Storage/storageAccounts". - :vartype type: str - :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy - information. - :vartype system_data: ~azure.mgmt.cosmosdb.models.SystemData - :ivar provisioning_state: A provisioning state of the ThroughputPool Account. Known values are: - "Uninitialized", "Initializing", "InternallyReady", "Online", "Deleting", "Succeeded", - "Failed", "Canceled", and "Updating". - :vartype provisioning_state: str or ~azure.mgmt.cosmosdb.models.Status - :ivar account_resource_identifier: The resource identifier of global database account in the - throughputPool. - :vartype account_resource_identifier: str - :ivar account_location: The location of global database account in the throughputPool. - :vartype account_location: str - :ivar account_instance_id: The instance id of global database account in the throughputPool. - :vartype account_instance_id: str - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "system_data": {"readonly": True}, - "account_instance_id": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "system_data": {"key": "systemData", "type": "SystemData"}, - "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, - "account_resource_identifier": {"key": "properties.accountResourceIdentifier", "type": "str"}, - "account_location": {"key": "properties.accountLocation", "type": "str"}, - "account_instance_id": {"key": "properties.accountInstanceId", "type": "str"}, - } - - def __init__( - self, - *, - provisioning_state: Optional[Union[str, "_models.Status"]] = None, - account_resource_identifier: Optional[str] = None, - account_location: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword provisioning_state: A provisioning state of the ThroughputPool Account. Known values - are: "Uninitialized", "Initializing", "InternallyReady", "Online", "Deleting", "Succeeded", - "Failed", "Canceled", and "Updating". - :paramtype provisioning_state: str or ~azure.mgmt.cosmosdb.models.Status - :keyword account_resource_identifier: The resource identifier of global database account in the - throughputPool. - :paramtype account_resource_identifier: str - :keyword account_location: The location of global database account in the throughputPool. - :paramtype account_location: str - """ - super().__init__(**kwargs) - self.provisioning_state = provisioning_state - self.account_resource_identifier = account_resource_identifier - self.account_location = account_location - self.account_instance_id = None - - -class ThroughputPoolAccountsListResult(_serialization.Model): - """The List operation response, that contains the global database accounts and their properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of global database accounts in a throughput pool and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.ThroughputPoolAccountResource] - :ivar next_link: The link used to get the next page of results. - :vartype next_link: str - """ - - _validation = { - "value": {"readonly": True}, - "next_link": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[ThroughputPoolAccountResource]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - self.next_link = None - - -class TrackedResource(Resource): - """The resource model definition for an Azure Resource Manager tracked top level resource which - has 'tags' and a 'location'. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar id: Fully qualified resource ID for the resource. E.g. - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or - "Microsoft.Storage/storageAccounts". - :vartype type: str - :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy - information. - :vartype system_data: ~azure.mgmt.cosmosdb.models.SystemData - :ivar tags: Resource tags. - :vartype tags: dict[str, str] - :ivar location: The geo-location where the resource lives. Required. - :vartype location: str - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "system_data": {"readonly": True}, - "location": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "system_data": {"key": "systemData", "type": "SystemData"}, - "tags": {"key": "tags", "type": "{str}"}, - "location": {"key": "location", "type": "str"}, - } - - def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kwargs: Any) -> None: - """ - :keyword tags: Resource tags. - :paramtype tags: dict[str, str] - :keyword location: The geo-location where the resource lives. Required. - :paramtype location: str - """ - super().__init__(**kwargs) - self.tags = tags - self.location = location - - -class ThroughputPoolResource(TrackedResource): - """An Azure Cosmos DB Throughputpool. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar id: Fully qualified resource ID for the resource. E.g. - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or - "Microsoft.Storage/storageAccounts". - :vartype type: str - :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy - information. - :vartype system_data: ~azure.mgmt.cosmosdb.models.SystemData - :ivar tags: Resource tags. - :vartype tags: dict[str, str] - :ivar location: The geo-location where the resource lives. Required. - :vartype location: str - :ivar provisioning_state: A provisioning state of the ThroughputPool. Known values are: - "Uninitialized", "Initializing", "InternallyReady", "Online", "Deleting", "Succeeded", - "Failed", "Canceled", and "Updating". - :vartype provisioning_state: str or ~azure.mgmt.cosmosdb.models.Status - :ivar max_throughput: Value for throughput to be shared among CosmosDB resources in the pool. - :vartype max_throughput: int - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "system_data": {"readonly": True}, - "location": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "system_data": {"key": "systemData", "type": "SystemData"}, - "tags": {"key": "tags", "type": "{str}"}, - "location": {"key": "location", "type": "str"}, - "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, - "max_throughput": {"key": "properties.maxThroughput", "type": "int"}, - } - - def __init__( - self, - *, - location: str, - tags: Optional[Dict[str, str]] = None, - provisioning_state: Optional[Union[str, "_models.Status"]] = None, - max_throughput: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword tags: Resource tags. - :paramtype tags: dict[str, str] - :keyword location: The geo-location where the resource lives. Required. - :paramtype location: str - :keyword provisioning_state: A provisioning state of the ThroughputPool. Known values are: - "Uninitialized", "Initializing", "InternallyReady", "Online", "Deleting", "Succeeded", - "Failed", "Canceled", and "Updating". - :paramtype provisioning_state: str or ~azure.mgmt.cosmosdb.models.Status - :keyword max_throughput: Value for throughput to be shared among CosmosDB resources in the - pool. - :paramtype max_throughput: int - """ - super().__init__(tags=tags, location=location, **kwargs) - self.provisioning_state = provisioning_state - self.max_throughput = max_throughput - - -class ThroughputPoolsListResult(_serialization.Model): - """The List operation response, that contains the throughput pools and their properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of throughput pools and their properties. - :vartype value: list[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] - :ivar next_link: The link used to get the next page of results. - :vartype next_link: str - """ - - _validation = { - "value": {"readonly": True}, - "next_link": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[ThroughputPoolResource]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - self.next_link = None - - -class ThroughputPoolUpdate(_serialization.Model): - """Represents a throughput pool resource for updates. - - :ivar provisioning_state: A provisioning state of the ThroughputPool. Known values are: - "Uninitialized", "Initializing", "InternallyReady", "Online", "Deleting", "Succeeded", - "Failed", "Canceled", and "Updating". - :vartype provisioning_state: str or ~azure.mgmt.cosmosdb.models.Status - :ivar max_throughput: Value for throughput to be shared among CosmosDB resources in the pool. - :vartype max_throughput: int - """ - - _attribute_map = { - "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, - "max_throughput": {"key": "properties.maxThroughput", "type": "int"}, - } - - def __init__( - self, - *, - provisioning_state: Optional[Union[str, "_models.Status"]] = None, - max_throughput: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword provisioning_state: A provisioning state of the ThroughputPool. Known values are: - "Uninitialized", "Initializing", "InternallyReady", "Online", "Deleting", "Succeeded", - "Failed", "Canceled", and "Updating". - :paramtype provisioning_state: str or ~azure.mgmt.cosmosdb.models.Status - :keyword max_throughput: Value for throughput to be shared among CosmosDB resources in the - pool. - :paramtype max_throughput: int - """ - super().__init__(**kwargs) - self.provisioning_state = provisioning_state - self.max_throughput = max_throughput - - -class ThroughputSettingsResource(_serialization.Model): - """Cosmos DB resource throughput object. Either throughput is required or autoscaleSettings is - required, but not both. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar throughput: Value of the Cosmos DB resource throughput. Either throughput is required or - autoscaleSettings is required, but not both. - :vartype throughput: int - :ivar autoscale_settings: Cosmos DB resource for autoscale settings. Either throughput is - required or autoscaleSettings is required, but not both. - :vartype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettingsResource - :ivar minimum_throughput: The minimum throughput of the resource. - :vartype minimum_throughput: str - :ivar offer_replace_pending: The throughput replace is pending. - :vartype offer_replace_pending: str - :ivar instant_maximum_throughput: The offer throughput value to instantly scale up without - triggering splits. - :vartype instant_maximum_throughput: str - :ivar soft_allowed_maximum_throughput: The maximum throughput value or the maximum - maxThroughput value (for autoscale) that can be specified. - :vartype soft_allowed_maximum_throughput: str - """ - - _validation = { - "minimum_throughput": {"readonly": True}, - "offer_replace_pending": {"readonly": True}, - "instant_maximum_throughput": {"readonly": True}, - "soft_allowed_maximum_throughput": {"readonly": True}, - } - - _attribute_map = { - "throughput": {"key": "throughput", "type": "int"}, - "autoscale_settings": {"key": "autoscaleSettings", "type": "AutoscaleSettingsResource"}, - "minimum_throughput": {"key": "minimumThroughput", "type": "str"}, - "offer_replace_pending": {"key": "offerReplacePending", "type": "str"}, - "instant_maximum_throughput": {"key": "instantMaximumThroughput", "type": "str"}, - "soft_allowed_maximum_throughput": {"key": "softAllowedMaximumThroughput", "type": "str"}, - } - - def __init__( - self, - *, - throughput: Optional[int] = None, - autoscale_settings: Optional["_models.AutoscaleSettingsResource"] = None, - **kwargs: Any - ) -> None: - """ - :keyword throughput: Value of the Cosmos DB resource throughput. Either throughput is required - or autoscaleSettings is required, but not both. - :paramtype throughput: int - :keyword autoscale_settings: Cosmos DB resource for autoscale settings. Either throughput is - required or autoscaleSettings is required, but not both. - :paramtype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettingsResource - """ - super().__init__(**kwargs) - self.throughput = throughput - self.autoscale_settings = autoscale_settings - self.minimum_throughput = None - self.offer_replace_pending = None - self.instant_maximum_throughput = None - self.soft_allowed_maximum_throughput = None - - -class ThroughputSettingsGetPropertiesResource(ThroughputSettingsResource, ExtendedResourceProperties): - """ThroughputSettingsGetPropertiesResource. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar rid: A system generated property. A unique identifier. - :vartype rid: str - :ivar ts: A system generated property that denotes the last updated timestamp of the resource. - :vartype ts: float - :ivar etag: A system generated property representing the resource etag required for optimistic - concurrency control. - :vartype etag: str - :ivar throughput: Value of the Cosmos DB resource throughput. Either throughput is required or - autoscaleSettings is required, but not both. - :vartype throughput: int - :ivar autoscale_settings: Cosmos DB resource for autoscale settings. Either throughput is - required or autoscaleSettings is required, but not both. - :vartype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettingsResource - :ivar minimum_throughput: The minimum throughput of the resource. - :vartype minimum_throughput: str - :ivar offer_replace_pending: The throughput replace is pending. - :vartype offer_replace_pending: str - :ivar instant_maximum_throughput: The offer throughput value to instantly scale up without - triggering splits. - :vartype instant_maximum_throughput: str - :ivar soft_allowed_maximum_throughput: The maximum throughput value or the maximum - maxThroughput value (for autoscale) that can be specified. - :vartype soft_allowed_maximum_throughput: str - """ - - _validation = { - "rid": {"readonly": True}, - "ts": {"readonly": True}, - "etag": {"readonly": True}, - "minimum_throughput": {"readonly": True}, - "offer_replace_pending": {"readonly": True}, - "instant_maximum_throughput": {"readonly": True}, - "soft_allowed_maximum_throughput": {"readonly": True}, - } - - _attribute_map = { - "rid": {"key": "_rid", "type": "str"}, - "ts": {"key": "_ts", "type": "float"}, - "etag": {"key": "_etag", "type": "str"}, - "throughput": {"key": "throughput", "type": "int"}, - "autoscale_settings": {"key": "autoscaleSettings", "type": "AutoscaleSettingsResource"}, - "minimum_throughput": {"key": "minimumThroughput", "type": "str"}, - "offer_replace_pending": {"key": "offerReplacePending", "type": "str"}, - "instant_maximum_throughput": {"key": "instantMaximumThroughput", "type": "str"}, - "soft_allowed_maximum_throughput": {"key": "softAllowedMaximumThroughput", "type": "str"}, - } - - def __init__( - self, - *, - throughput: Optional[int] = None, - autoscale_settings: Optional["_models.AutoscaleSettingsResource"] = None, - **kwargs: Any - ) -> None: - """ - :keyword throughput: Value of the Cosmos DB resource throughput. Either throughput is required - or autoscaleSettings is required, but not both. - :paramtype throughput: int - :keyword autoscale_settings: Cosmos DB resource for autoscale settings. Either throughput is - required or autoscaleSettings is required, but not both. - :paramtype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettingsResource - """ - super().__init__(throughput=throughput, autoscale_settings=autoscale_settings, **kwargs) - self.rid = None - self.ts = None - self.etag = None - self.throughput = throughput - self.autoscale_settings = autoscale_settings - self.minimum_throughput = None - self.offer_replace_pending = None - self.instant_maximum_throughput = None - self.soft_allowed_maximum_throughput = None - - -class ThroughputSettingsGetResults(ARMResourceProperties): - """An Azure Cosmos DB resource throughput. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: - :vartype resource: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetPropertiesResource - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "ThroughputSettingsGetPropertiesResource"}, - } - - def __init__( - self, - *, - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - resource: Optional["_models.ThroughputSettingsGetPropertiesResource"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: - :paramtype resource: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetPropertiesResource - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - - -class ThroughputSettingsUpdateParameters(ARMResourceProperties): - """Parameters to update Cosmos DB resource throughput. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar id: The unique resource identifier of the ARM resource. - :vartype id: str - :ivar name: The name of the ARM resource. - :vartype name: str - :ivar type: The type of Azure resource. - :vartype type: str - :ivar location: The location of the resource group to which the resource belongs. - :vartype location: str - :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :vartype tags: dict[str, str] - :ivar identity: Identity for the resource. - :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :ivar resource: The standard JSON format of a resource throughput. Required. - :vartype resource: ~azure.mgmt.cosmosdb.models.ThroughputSettingsResource - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "resource": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "resource": {"key": "properties.resource", "type": "ThroughputSettingsResource"}, - } - - def __init__( - self, - *, - resource: "_models.ThroughputSettingsResource", - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The location of the resource group to which the resource belongs. - :paramtype location: str - :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be - used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can - be provided for a resource. Each tag must have a key no greater than 128 characters and value - no greater than 256 characters. For example, the default experience for a template type is set - with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", - "Graph", "DocumentDB", and "MongoDB". - :paramtype tags: dict[str, str] - :keyword identity: Identity for the resource. - :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity - :keyword resource: The standard JSON format of a resource throughput. Required. - :paramtype resource: ~azure.mgmt.cosmosdb.models.ThroughputSettingsResource - """ - super().__init__(location=location, tags=tags, identity=identity, **kwargs) - self.resource = resource - - -class UniqueKey(_serialization.Model): - """The unique key on that enforces uniqueness constraint on documents in the collection in the - Azure Cosmos DB service. - - :ivar paths: List of paths must be unique for each document in the Azure Cosmos DB service. - :vartype paths: list[str] - """ - - _attribute_map = { - "paths": {"key": "paths", "type": "[str]"}, - } - - def __init__(self, *, paths: Optional[List[str]] = None, **kwargs: Any) -> None: - """ - :keyword paths: List of paths must be unique for each document in the Azure Cosmos DB service. - :paramtype paths: list[str] - """ - super().__init__(**kwargs) - self.paths = paths - - -class UniqueKeyPolicy(_serialization.Model): - """The unique key policy configuration for specifying uniqueness constraints on documents in the - collection in the Azure Cosmos DB service. - - :ivar unique_keys: List of unique keys on that enforces uniqueness constraint on documents in - the collection in the Azure Cosmos DB service. - :vartype unique_keys: list[~azure.mgmt.cosmosdb.models.UniqueKey] - """ - - _attribute_map = { - "unique_keys": {"key": "uniqueKeys", "type": "[UniqueKey]"}, - } - - def __init__(self, *, unique_keys: Optional[List["_models.UniqueKey"]] = None, **kwargs: Any) -> None: - """ - :keyword unique_keys: List of unique keys on that enforces uniqueness constraint on documents - in the collection in the Azure Cosmos DB service. - :paramtype unique_keys: list[~azure.mgmt.cosmosdb.models.UniqueKey] - """ - super().__init__(**kwargs) - self.unique_keys = unique_keys - - -class UsagesResult(_serialization.Model): - """The response to a list usage request. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of usages for the database. A usage is a point in time metric. - :vartype value: list[~azure.mgmt.cosmosdb.models.Usage] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[Usage]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.value = None - - -class VirtualNetworkRule(_serialization.Model): - """Virtual Network ACL Rule object. - - :ivar id: Resource ID of a subnet, for example: - /subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}. # pylint: disable=line-too-long - :vartype id: str - :ivar ignore_missing_v_net_service_endpoint: Create firewall rule before the virtual network - has vnet service endpoint enabled. - :vartype ignore_missing_v_net_service_endpoint: bool - """ - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "ignore_missing_v_net_service_endpoint": {"key": "ignoreMissingVNetServiceEndpoint", "type": "bool"}, - } - - def __init__( - self, - *, - id: Optional[str] = None, # pylint: disable=redefined-builtin - ignore_missing_v_net_service_endpoint: Optional[bool] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: Resource ID of a subnet, for example: - /subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}. # pylint: disable=line-too-long - :paramtype id: str - :keyword ignore_missing_v_net_service_endpoint: Create firewall rule before the virtual network - has vnet service endpoint enabled. - :paramtype ignore_missing_v_net_service_endpoint: bool - """ - super().__init__(**kwargs) - self.id = id - self.ignore_missing_v_net_service_endpoint = ignore_missing_v_net_service_endpoint +# coding=utf-8 +# pylint: disable=too-many-lines +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import datetime +import sys +from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union + +from .. import _serialization + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models +JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object + + +class AccessRule(_serialization.Model): + """Access rule in a network security perimeter configuration profile. + + :ivar name: Name of the access rule. + :vartype name: str + :ivar properties: Properties of Access Rule. + :vartype properties: ~azure.mgmt.cosmosdb.models.AccessRuleProperties + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "properties": {"key": "properties", "type": "AccessRuleProperties"}, + } + + def __init__( + self, *, name: Optional[str] = None, properties: Optional["_models.AccessRuleProperties"] = None, **kwargs: Any + ) -> None: + """ + :keyword name: Name of the access rule. + :paramtype name: str + :keyword properties: Properties of Access Rule. + :paramtype properties: ~azure.mgmt.cosmosdb.models.AccessRuleProperties + """ + super().__init__(**kwargs) + self.name = name + self.properties = properties + + +class AccessRuleProperties(_serialization.Model): + """Properties of Access Rule. + + :ivar direction: Direction of Access Rule. Known values are: "Inbound" and "Outbound". + :vartype direction: str or ~azure.mgmt.cosmosdb.models.AccessRuleDirection + :ivar address_prefixes: Address prefixes in the CIDR format for inbound rules. + :vartype address_prefixes: list[str] + :ivar subscriptions: Subscriptions for inbound rules. + :vartype subscriptions: list[~azure.mgmt.cosmosdb.models.AccessRulePropertiesSubscriptionsItem] + :ivar network_security_perimeters: Network security perimeters for inbound rules. + :vartype network_security_perimeters: + list[~azure.mgmt.cosmosdb.models.NetworkSecurityPerimeter] + :ivar fully_qualified_domain_names: Fully qualified domain names (FQDN) for outbound rules. + :vartype fully_qualified_domain_names: list[str] + :ivar email_addresses: Email addresses for outbound rules. + :vartype email_addresses: list[str] + :ivar phone_numbers: Phone numbers for outbound rules. + :vartype phone_numbers: list[str] + """ + + _attribute_map = { + "direction": {"key": "direction", "type": "str"}, + "address_prefixes": {"key": "addressPrefixes", "type": "[str]"}, + "subscriptions": {"key": "subscriptions", "type": "[AccessRulePropertiesSubscriptionsItem]"}, + "network_security_perimeters": {"key": "networkSecurityPerimeters", "type": "[NetworkSecurityPerimeter]"}, + "fully_qualified_domain_names": {"key": "fullyQualifiedDomainNames", "type": "[str]"}, + "email_addresses": {"key": "emailAddresses", "type": "[str]"}, + "phone_numbers": {"key": "phoneNumbers", "type": "[str]"}, + } + + def __init__( + self, + *, + direction: Optional[Union[str, "_models.AccessRuleDirection"]] = None, + address_prefixes: Optional[List[str]] = None, + subscriptions: Optional[List["_models.AccessRulePropertiesSubscriptionsItem"]] = None, + network_security_perimeters: Optional[List["_models.NetworkSecurityPerimeter"]] = None, + fully_qualified_domain_names: Optional[List[str]] = None, + email_addresses: Optional[List[str]] = None, + phone_numbers: Optional[List[str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword direction: Direction of Access Rule. Known values are: "Inbound" and "Outbound". + :paramtype direction: str or ~azure.mgmt.cosmosdb.models.AccessRuleDirection + :keyword address_prefixes: Address prefixes in the CIDR format for inbound rules. + :paramtype address_prefixes: list[str] + :keyword subscriptions: Subscriptions for inbound rules. + :paramtype subscriptions: + list[~azure.mgmt.cosmosdb.models.AccessRulePropertiesSubscriptionsItem] + :keyword network_security_perimeters: Network security perimeters for inbound rules. + :paramtype network_security_perimeters: + list[~azure.mgmt.cosmosdb.models.NetworkSecurityPerimeter] + :keyword fully_qualified_domain_names: Fully qualified domain names (FQDN) for outbound rules. + :paramtype fully_qualified_domain_names: list[str] + :keyword email_addresses: Email addresses for outbound rules. + :paramtype email_addresses: list[str] + :keyword phone_numbers: Phone numbers for outbound rules. + :paramtype phone_numbers: list[str] + """ + super().__init__(**kwargs) + self.direction = direction + self.address_prefixes = address_prefixes + self.subscriptions = subscriptions + self.network_security_perimeters = network_security_perimeters + self.fully_qualified_domain_names = fully_qualified_domain_names + self.email_addresses = email_addresses + self.phone_numbers = phone_numbers + + +class AccessRulePropertiesSubscriptionsItem(_serialization.Model): + """Subscription identifiers. + + :ivar id: The fully qualified Azure resource ID of the subscription e.g. + ('/subscriptions/00000000-0000-0000-0000-000000000000'). + :vartype id: str + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + } + + def __init__(self, *, id: Optional[str] = None, **kwargs: Any) -> None: # pylint: disable=redefined-builtin + """ + :keyword id: The fully qualified Azure resource ID of the subscription e.g. + ('/subscriptions/00000000-0000-0000-0000-000000000000'). + :paramtype id: str + """ + super().__init__(**kwargs) + self.id = id + + +class AccountKeyMetadata(_serialization.Model): + """The metadata related to an access key for a given database account. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar generation_time: Generation time in UTC of the key in ISO-8601 format. If the value is + missing from the object, it means that the last key regeneration was triggered before + 2022-06-18. + :vartype generation_time: ~datetime.datetime + """ + + _validation = { + "generation_time": {"readonly": True}, + } + + _attribute_map = { + "generation_time": {"key": "generationTime", "type": "iso-8601"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.generation_time = None + + +class AnalyticalStorageConfiguration(_serialization.Model): + """Analytical storage specific properties. + + :ivar schema_type: Describes the types of schema for analytical storage. Known values are: + "WellDefined" and "FullFidelity". + :vartype schema_type: str or ~azure.mgmt.cosmosdb.models.AnalyticalStorageSchemaType + """ + + _attribute_map = { + "schema_type": {"key": "schemaType", "type": "str"}, + } + + def __init__( + self, *, schema_type: Optional[Union[str, "_models.AnalyticalStorageSchemaType"]] = None, **kwargs: Any + ) -> None: + """ + :keyword schema_type: Describes the types of schema for analytical storage. Known values are: + "WellDefined" and "FullFidelity". + :paramtype schema_type: str or ~azure.mgmt.cosmosdb.models.AnalyticalStorageSchemaType + """ + super().__init__(**kwargs) + self.schema_type = schema_type + + +class ApiProperties(_serialization.Model): + """ApiProperties. + + :ivar server_version: Describes the version of the MongoDB account. Known values are: "3.2", + "3.6", "4.0", "4.2", "5.0", "6.0", and "7.0". + :vartype server_version: str or ~azure.mgmt.cosmosdb.models.ServerVersion + """ + + _attribute_map = { + "server_version": {"key": "serverVersion", "type": "str"}, + } + + def __init__(self, *, server_version: Optional[Union[str, "_models.ServerVersion"]] = None, **kwargs: Any) -> None: + """ + :keyword server_version: Describes the version of the MongoDB account. Known values are: "3.2", + "3.6", "4.0", "4.2", "5.0", "6.0", and "7.0". + :paramtype server_version: str or ~azure.mgmt.cosmosdb.models.ServerVersion + """ + super().__init__(**kwargs) + self.server_version = server_version + + +class ARMProxyResource(_serialization.Model): + """The resource model definition for a ARM proxy resource. It will have everything other than + required location and tags. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the database account. + :vartype id: str + :ivar name: The name of the database account. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + + +class ARMResourceProperties(_serialization.Model): + """The core properties of ARM resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.location = location + self.tags = tags + self.identity = identity + + +class AuthenticationMethodLdapProperties(_serialization.Model): + """Ldap authentication method properties. This feature is in preview. + + :ivar server_hostname: Hostname of the LDAP server. + :vartype server_hostname: str + :ivar server_port: Port of the LDAP server. + :vartype server_port: int + :ivar service_user_distinguished_name: Distinguished name of the look up user account, who can + look up user details on authentication. + :vartype service_user_distinguished_name: str + :ivar service_user_password: Password of the look up user. + :vartype service_user_password: str + :ivar search_base_distinguished_name: Distinguished name of the object to start the recursive + search of users from. + :vartype search_base_distinguished_name: str + :ivar search_filter_template: Template to use for searching. Defaults to (cn=%s) where %s will + be replaced by the username used to login. + :vartype search_filter_template: str + :ivar server_certificates: + :vartype server_certificates: list[~azure.mgmt.cosmosdb.models.Certificate] + :ivar connection_timeout_in_ms: Timeout for connecting to the LDAP server in miliseconds. The + default is 5000 ms. + :vartype connection_timeout_in_ms: int + """ + + _attribute_map = { + "server_hostname": {"key": "serverHostname", "type": "str"}, + "server_port": {"key": "serverPort", "type": "int"}, + "service_user_distinguished_name": {"key": "serviceUserDistinguishedName", "type": "str"}, + "service_user_password": {"key": "serviceUserPassword", "type": "str"}, + "search_base_distinguished_name": {"key": "searchBaseDistinguishedName", "type": "str"}, + "search_filter_template": {"key": "searchFilterTemplate", "type": "str"}, + "server_certificates": {"key": "serverCertificates", "type": "[Certificate]"}, + "connection_timeout_in_ms": {"key": "connectionTimeoutInMs", "type": "int"}, + } + + def __init__( + self, + *, + server_hostname: Optional[str] = None, + server_port: Optional[int] = None, + service_user_distinguished_name: Optional[str] = None, + service_user_password: Optional[str] = None, + search_base_distinguished_name: Optional[str] = None, + search_filter_template: Optional[str] = None, + server_certificates: Optional[List["_models.Certificate"]] = None, + connection_timeout_in_ms: Optional[int] = None, + **kwargs: Any + ) -> None: + """ + :keyword server_hostname: Hostname of the LDAP server. + :paramtype server_hostname: str + :keyword server_port: Port of the LDAP server. + :paramtype server_port: int + :keyword service_user_distinguished_name: Distinguished name of the look up user account, who + can look up user details on authentication. + :paramtype service_user_distinguished_name: str + :keyword service_user_password: Password of the look up user. + :paramtype service_user_password: str + :keyword search_base_distinguished_name: Distinguished name of the object to start the + recursive search of users from. + :paramtype search_base_distinguished_name: str + :keyword search_filter_template: Template to use for searching. Defaults to (cn=%s) where %s + will be replaced by the username used to login. + :paramtype search_filter_template: str + :keyword server_certificates: + :paramtype server_certificates: list[~azure.mgmt.cosmosdb.models.Certificate] + :keyword connection_timeout_in_ms: Timeout for connecting to the LDAP server in miliseconds. + The default is 5000 ms. + :paramtype connection_timeout_in_ms: int + """ + super().__init__(**kwargs) + self.server_hostname = server_hostname + self.server_port = server_port + self.service_user_distinguished_name = service_user_distinguished_name + self.service_user_password = service_user_password + self.search_base_distinguished_name = search_base_distinguished_name + self.search_filter_template = search_filter_template + self.server_certificates = server_certificates + self.connection_timeout_in_ms = connection_timeout_in_ms + + +class AutoscaleSettings(_serialization.Model): + """AutoscaleSettings. + + :ivar max_throughput: Represents maximum throughput, the resource can scale up to. + :vartype max_throughput: int + """ + + _attribute_map = { + "max_throughput": {"key": "maxThroughput", "type": "int"}, + } + + def __init__(self, *, max_throughput: Optional[int] = None, **kwargs: Any) -> None: + """ + :keyword max_throughput: Represents maximum throughput, the resource can scale up to. + :paramtype max_throughput: int + """ + super().__init__(**kwargs) + self.max_throughput = max_throughput + + +class AutoscaleSettingsResource(_serialization.Model): + """Cosmos DB provisioned throughput settings object. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar max_throughput: Represents maximum throughput container can scale up to. Required. + :vartype max_throughput: int + :ivar auto_upgrade_policy: Cosmos DB resource auto-upgrade policy. + :vartype auto_upgrade_policy: ~azure.mgmt.cosmosdb.models.AutoUpgradePolicyResource + :ivar target_max_throughput: Represents target maximum throughput container can scale up to + once offer is no longer in pending state. + :vartype target_max_throughput: int + """ + + _validation = { + "max_throughput": {"required": True}, + "target_max_throughput": {"readonly": True}, + } + + _attribute_map = { + "max_throughput": {"key": "maxThroughput", "type": "int"}, + "auto_upgrade_policy": {"key": "autoUpgradePolicy", "type": "AutoUpgradePolicyResource"}, + "target_max_throughput": {"key": "targetMaxThroughput", "type": "int"}, + } + + def __init__( + self, + *, + max_throughput: int, + auto_upgrade_policy: Optional["_models.AutoUpgradePolicyResource"] = None, + **kwargs: Any + ) -> None: + """ + :keyword max_throughput: Represents maximum throughput container can scale up to. Required. + :paramtype max_throughput: int + :keyword auto_upgrade_policy: Cosmos DB resource auto-upgrade policy. + :paramtype auto_upgrade_policy: ~azure.mgmt.cosmosdb.models.AutoUpgradePolicyResource + """ + super().__init__(**kwargs) + self.max_throughput = max_throughput + self.auto_upgrade_policy = auto_upgrade_policy + self.target_max_throughput = None + + +class AutoUpgradePolicyResource(_serialization.Model): + """Cosmos DB resource auto-upgrade policy. + + :ivar throughput_policy: Represents throughput policy which service must adhere to for + auto-upgrade. + :vartype throughput_policy: ~azure.mgmt.cosmosdb.models.ThroughputPolicyResource + """ + + _attribute_map = { + "throughput_policy": {"key": "throughputPolicy", "type": "ThroughputPolicyResource"}, + } + + def __init__( + self, *, throughput_policy: Optional["_models.ThroughputPolicyResource"] = None, **kwargs: Any + ) -> None: + """ + :keyword throughput_policy: Represents throughput policy which service must adhere to for + auto-upgrade. + :paramtype throughput_policy: ~azure.mgmt.cosmosdb.models.ThroughputPolicyResource + """ + super().__init__(**kwargs) + self.throughput_policy = throughput_policy + + +class DataTransferDataSourceSink(_serialization.Model): + """Base class for all DataTransfer source/sink. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + AzureBlobDataTransferDataSourceSink, BaseCosmosDataTransferDataSourceSink, + CosmosMongoVCoreDataTransferDataSourceSink + + All required parameters must be populated in order to send to server. + + :ivar component: Known values are: "CosmosDBCassandra", "CosmosDBMongo", "CosmosDBMongoVCore", + "CosmosDBSql", and "AzureBlobStorage". + :vartype component: str or ~azure.mgmt.cosmosdb.models.DataTransferComponent + """ + + _validation = { + "component": {"required": True}, + } + + _attribute_map = { + "component": {"key": "component", "type": "str"}, + } + + _subtype_map = { + "component": { + "AzureBlobStorage": "AzureBlobDataTransferDataSourceSink", + "BaseCosmosDataTransferDataSourceSink": "BaseCosmosDataTransferDataSourceSink", + "CosmosDBMongoVCore": "CosmosMongoVCoreDataTransferDataSourceSink", + } + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.component: Optional[str] = None + + +class AzureBlobDataTransferDataSourceSink(DataTransferDataSourceSink): + """An Azure Blob Storage data source/sink. + + All required parameters must be populated in order to send to server. + + :ivar component: Known values are: "CosmosDBCassandra", "CosmosDBMongo", "CosmosDBMongoVCore", + "CosmosDBSql", and "AzureBlobStorage". + :vartype component: str or ~azure.mgmt.cosmosdb.models.DataTransferComponent + :ivar container_name: Required. + :vartype container_name: str + :ivar endpoint_url: + :vartype endpoint_url: str + """ + + _validation = { + "component": {"required": True}, + "container_name": {"required": True}, + } + + _attribute_map = { + "component": {"key": "component", "type": "str"}, + "container_name": {"key": "containerName", "type": "str"}, + "endpoint_url": {"key": "endpointUrl", "type": "str"}, + } + + def __init__(self, *, container_name: str, endpoint_url: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword container_name: Required. + :paramtype container_name: str + :keyword endpoint_url: + :paramtype endpoint_url: str + """ + super().__init__(**kwargs) + self.component: str = "AzureBlobStorage" + self.container_name = container_name + self.endpoint_url = endpoint_url + + +class BackupInformation(_serialization.Model): + """Backup information of a resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar continuous_backup_information: Information about the status of continuous backups. + :vartype continuous_backup_information: ~azure.mgmt.cosmosdb.models.ContinuousBackupInformation + """ + + _validation = { + "continuous_backup_information": {"readonly": True}, + } + + _attribute_map = { + "continuous_backup_information": {"key": "continuousBackupInformation", "type": "ContinuousBackupInformation"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.continuous_backup_information = None + + +class BackupPolicy(_serialization.Model): + """The object representing the policy for taking backups on an account. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + ContinuousModeBackupPolicy, PeriodicModeBackupPolicy + + All required parameters must be populated in order to send to server. + + :ivar type: Describes the mode of backups. Required. Known values are: "Periodic" and + "Continuous". + :vartype type: str or ~azure.mgmt.cosmosdb.models.BackupPolicyType + :ivar migration_state: The object representing the state of the migration between the backup + policies. + :vartype migration_state: ~azure.mgmt.cosmosdb.models.BackupPolicyMigrationState + """ + + _validation = { + "type": {"required": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "migration_state": {"key": "migrationState", "type": "BackupPolicyMigrationState"}, + } + + _subtype_map = {"type": {"Continuous": "ContinuousModeBackupPolicy", "Periodic": "PeriodicModeBackupPolicy"}} + + def __init__( + self, *, migration_state: Optional["_models.BackupPolicyMigrationState"] = None, **kwargs: Any + ) -> None: + """ + :keyword migration_state: The object representing the state of the migration between the backup + policies. + :paramtype migration_state: ~azure.mgmt.cosmosdb.models.BackupPolicyMigrationState + """ + super().__init__(**kwargs) + self.type: Optional[str] = None + self.migration_state = migration_state + + +class BackupPolicyMigrationState(_serialization.Model): + """The object representing the state of the migration between the backup policies. + + :ivar status: Describes the status of migration between backup policy types. Known values are: + "Invalid", "InProgress", "Completed", and "Failed". + :vartype status: str or ~azure.mgmt.cosmosdb.models.BackupPolicyMigrationStatus + :ivar target_type: Describes the target backup policy type of the backup policy migration. + Known values are: "Periodic" and "Continuous". + :vartype target_type: str or ~azure.mgmt.cosmosdb.models.BackupPolicyType + :ivar start_time: Time at which the backup policy migration started (ISO-8601 format). + :vartype start_time: ~datetime.datetime + """ + + _attribute_map = { + "status": {"key": "status", "type": "str"}, + "target_type": {"key": "targetType", "type": "str"}, + "start_time": {"key": "startTime", "type": "iso-8601"}, + } + + def __init__( + self, + *, + status: Optional[Union[str, "_models.BackupPolicyMigrationStatus"]] = None, + target_type: Optional[Union[str, "_models.BackupPolicyType"]] = None, + start_time: Optional[datetime.datetime] = None, + **kwargs: Any + ) -> None: + """ + :keyword status: Describes the status of migration between backup policy types. Known values + are: "Invalid", "InProgress", "Completed", and "Failed". + :paramtype status: str or ~azure.mgmt.cosmosdb.models.BackupPolicyMigrationStatus + :keyword target_type: Describes the target backup policy type of the backup policy migration. + Known values are: "Periodic" and "Continuous". + :paramtype target_type: str or ~azure.mgmt.cosmosdb.models.BackupPolicyType + :keyword start_time: Time at which the backup policy migration started (ISO-8601 format). + :paramtype start_time: ~datetime.datetime + """ + super().__init__(**kwargs) + self.status = status + self.target_type = target_type + self.start_time = start_time + + +class BackupResource(_serialization.Model): + """A restorable backup of a Cassandra cluster. + + :ivar backup_id: The unique identifier of backup. + :vartype backup_id: str + :ivar backup_state: The current state of the backup. Known values are: "Initiated", + "InProgress", "Succeeded", and "Failed". + :vartype backup_state: str or ~azure.mgmt.cosmosdb.models.BackupState + :ivar backup_start_timestamp: The time at which the backup process begins. + :vartype backup_start_timestamp: ~datetime.datetime + :ivar backup_stop_timestamp: The time at which the backup process ends. + :vartype backup_stop_timestamp: ~datetime.datetime + :ivar backup_expiry_timestamp: The time at which the backup will expire. + :vartype backup_expiry_timestamp: ~datetime.datetime + """ + + _attribute_map = { + "backup_id": {"key": "backupId", "type": "str"}, + "backup_state": {"key": "backupState", "type": "str"}, + "backup_start_timestamp": {"key": "backupStartTimestamp", "type": "iso-8601"}, + "backup_stop_timestamp": {"key": "backupStopTimestamp", "type": "iso-8601"}, + "backup_expiry_timestamp": {"key": "backupExpiryTimestamp", "type": "iso-8601"}, + } + + def __init__( + self, + *, + backup_id: Optional[str] = None, + backup_state: Optional[Union[str, "_models.BackupState"]] = None, + backup_start_timestamp: Optional[datetime.datetime] = None, + backup_stop_timestamp: Optional[datetime.datetime] = None, + backup_expiry_timestamp: Optional[datetime.datetime] = None, + **kwargs: Any + ) -> None: + """ + :keyword backup_id: The unique identifier of backup. + :paramtype backup_id: str + :keyword backup_state: The current state of the backup. Known values are: "Initiated", + "InProgress", "Succeeded", and "Failed". + :paramtype backup_state: str or ~azure.mgmt.cosmosdb.models.BackupState + :keyword backup_start_timestamp: The time at which the backup process begins. + :paramtype backup_start_timestamp: ~datetime.datetime + :keyword backup_stop_timestamp: The time at which the backup process ends. + :paramtype backup_stop_timestamp: ~datetime.datetime + :keyword backup_expiry_timestamp: The time at which the backup will expire. + :paramtype backup_expiry_timestamp: ~datetime.datetime + """ + super().__init__(**kwargs) + self.backup_id = backup_id + self.backup_state = backup_state + self.backup_start_timestamp = backup_start_timestamp + self.backup_stop_timestamp = backup_stop_timestamp + self.backup_expiry_timestamp = backup_expiry_timestamp + + +class BackupSchedule(_serialization.Model): + """BackupSchedule. + + :ivar schedule_name: The unique identifier of backup schedule. + :vartype schedule_name: str + :ivar cron_expression: The cron expression that defines when you want to back up your data. + :vartype cron_expression: str + :ivar retention_in_hours: The retention period (hours) of the backups. If you want to retain + data forever, set retention to 0. + :vartype retention_in_hours: int + """ + + _attribute_map = { + "schedule_name": {"key": "scheduleName", "type": "str"}, + "cron_expression": {"key": "cronExpression", "type": "str"}, + "retention_in_hours": {"key": "retentionInHours", "type": "int"}, + } + + def __init__( + self, + *, + schedule_name: Optional[str] = None, + cron_expression: Optional[str] = None, + retention_in_hours: Optional[int] = None, + **kwargs: Any + ) -> None: + """ + :keyword schedule_name: The unique identifier of backup schedule. + :paramtype schedule_name: str + :keyword cron_expression: The cron expression that defines when you want to back up your data. + :paramtype cron_expression: str + :keyword retention_in_hours: The retention period (hours) of the backups. If you want to retain + data forever, set retention to 0. + :paramtype retention_in_hours: int + """ + super().__init__(**kwargs) + self.schedule_name = schedule_name + self.cron_expression = cron_expression + self.retention_in_hours = retention_in_hours + + +class BaseCosmosDataTransferDataSourceSink(DataTransferDataSourceSink): + """A base CosmosDB data source/sink. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + CosmosCassandraDataTransferDataSourceSink, CosmosMongoDataTransferDataSourceSink, + CosmosSqlDataTransferDataSourceSink + + All required parameters must be populated in order to send to server. + + :ivar component: Known values are: "CosmosDBCassandra", "CosmosDBMongo", "CosmosDBMongoVCore", + "CosmosDBSql", and "AzureBlobStorage". + :vartype component: str or ~azure.mgmt.cosmosdb.models.DataTransferComponent + :ivar remote_account_name: + :vartype remote_account_name: str + """ + + _validation = { + "component": {"required": True}, + } + + _attribute_map = { + "component": {"key": "component", "type": "str"}, + "remote_account_name": {"key": "remoteAccountName", "type": "str"}, + } + + _subtype_map = { + "component": { + "CosmosDBCassandra": "CosmosCassandraDataTransferDataSourceSink", + "CosmosDBMongo": "CosmosMongoDataTransferDataSourceSink", + "CosmosDBSql": "CosmosSqlDataTransferDataSourceSink", + } + } + + def __init__(self, *, remote_account_name: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword remote_account_name: + :paramtype remote_account_name: str + """ + super().__init__(**kwargs) + self.component: str = "BaseCosmosDataTransferDataSourceSink" + self.remote_account_name = remote_account_name + + +class Capability(_serialization.Model): + """Cosmos DB capability object. + + :ivar name: Name of the Cosmos DB capability. For example, "name": "EnableCassandra". Current + values also include "EnableTable" and "EnableGremlin". + :vartype name: str + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + } + + def __init__(self, *, name: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword name: Name of the Cosmos DB capability. For example, "name": "EnableCassandra". + Current values also include "EnableTable" and "EnableGremlin". + :paramtype name: str + """ + super().__init__(**kwargs) + self.name = name + + +class Capacity(_serialization.Model): + """The object that represents all properties related to capacity enforcement on an account. + + :ivar total_throughput_limit: The total throughput limit imposed on the account. A + totalThroughputLimit of 2000 imposes a strict limit of max throughput that can be provisioned + on that account to be 2000. A totalThroughputLimit of -1 indicates no limits on provisioning of + throughput. + :vartype total_throughput_limit: int + """ + + _validation = { + "total_throughput_limit": {"minimum": -1}, + } + + _attribute_map = { + "total_throughput_limit": {"key": "totalThroughputLimit", "type": "int"}, + } + + def __init__(self, *, total_throughput_limit: Optional[int] = None, **kwargs: Any) -> None: + """ + :keyword total_throughput_limit: The total throughput limit imposed on the account. A + totalThroughputLimit of 2000 imposes a strict limit of max throughput that can be provisioned + on that account to be 2000. A totalThroughputLimit of -1 indicates no limits on provisioning of + throughput. + :paramtype total_throughput_limit: int + """ + super().__init__(**kwargs) + self.total_throughput_limit = total_throughput_limit + + +class CapacityModeChangeTransitionState(_serialization.Model): + """The transition state information related capacity mode change with update request. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar capacity_mode_transition_status: The transition status of capacity mode. Known values + are: "Invalid", "Initialized", "InProgress", "Completed", and "Failed". + :vartype capacity_mode_transition_status: str or + ~azure.mgmt.cosmosdb.models.CapacityModeTransitionStatus + :ivar current_capacity_mode: Indicates the current capacity mode of the account. Known values + are: "None", "Provisioned", and "Serverless". + :vartype current_capacity_mode: str or ~azure.mgmt.cosmosdb.models.CapacityMode + :ivar previous_capacity_mode: Indicates the previous capacity mode of the account before + successful transition. Known values are: "None", "Provisioned", and "Serverless". + :vartype previous_capacity_mode: str or ~azure.mgmt.cosmosdb.models.CapacityMode + :ivar capacity_mode_transition_begin_timestamp: Begin time in UTC of the capacity mode change. + :vartype capacity_mode_transition_begin_timestamp: ~datetime.datetime + :ivar capacity_mode_transition_end_timestamp: End time in UTC of the capacity mode change. + :vartype capacity_mode_transition_end_timestamp: ~datetime.datetime + :ivar capacity_mode_last_successful_transition_end_timestamp: End time in UTC of the last + successful capacity mode change. + :vartype capacity_mode_last_successful_transition_end_timestamp: ~datetime.datetime + """ + + _validation = { + "capacity_mode_transition_begin_timestamp": {"readonly": True}, + "capacity_mode_transition_end_timestamp": {"readonly": True}, + "capacity_mode_last_successful_transition_end_timestamp": {"readonly": True}, + } + + _attribute_map = { + "capacity_mode_transition_status": {"key": "capacityModeTransitionStatus", "type": "str"}, + "current_capacity_mode": {"key": "currentCapacityMode", "type": "str"}, + "previous_capacity_mode": {"key": "previousCapacityMode", "type": "str"}, + "capacity_mode_transition_begin_timestamp": {"key": "capacityModeTransitionBeginTimestamp", "type": "iso-8601"}, + "capacity_mode_transition_end_timestamp": {"key": "capacityModeTransitionEndTimestamp", "type": "iso-8601"}, + "capacity_mode_last_successful_transition_end_timestamp": { + "key": "capacityModeLastSuccessfulTransitionEndTimestamp", + "type": "iso-8601", + }, + } + + def __init__( + self, + *, + capacity_mode_transition_status: Optional[Union[str, "_models.CapacityModeTransitionStatus"]] = None, + current_capacity_mode: Optional[Union[str, "_models.CapacityMode"]] = None, + previous_capacity_mode: Optional[Union[str, "_models.CapacityMode"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword capacity_mode_transition_status: The transition status of capacity mode. Known values + are: "Invalid", "Initialized", "InProgress", "Completed", and "Failed". + :paramtype capacity_mode_transition_status: str or + ~azure.mgmt.cosmosdb.models.CapacityModeTransitionStatus + :keyword current_capacity_mode: Indicates the current capacity mode of the account. Known + values are: "None", "Provisioned", and "Serverless". + :paramtype current_capacity_mode: str or ~azure.mgmt.cosmosdb.models.CapacityMode + :keyword previous_capacity_mode: Indicates the previous capacity mode of the account before + successful transition. Known values are: "None", "Provisioned", and "Serverless". + :paramtype previous_capacity_mode: str or ~azure.mgmt.cosmosdb.models.CapacityMode + """ + super().__init__(**kwargs) + self.capacity_mode_transition_status = capacity_mode_transition_status + self.current_capacity_mode = current_capacity_mode + self.previous_capacity_mode = previous_capacity_mode + self.capacity_mode_transition_begin_timestamp = None + self.capacity_mode_transition_end_timestamp = None + self.capacity_mode_last_successful_transition_end_timestamp = None + + +class CassandraClusterDataCenterNodeItem(_serialization.Model): # pylint: disable=too-many-instance-attributes + """CassandraClusterDataCenterNodeItem. + + :ivar address: The node's IP address. + :vartype address: str + :ivar state: The state of the node in Cassandra ring. Known values are: "Normal", "Leaving", + "Joining", "Moving", and "Stopped". + :vartype state: str or ~azure.mgmt.cosmosdb.models.NodeState + :ivar status: + :vartype status: str + :ivar cassandra_process_status: Cassandra service status on this node. + :vartype cassandra_process_status: str + :ivar load: The amount of file system data in the data directory (e.g., 47.66 kB), excluding + all content in the snapshots subdirectories. Because all SSTable data files are included, any + data that is not cleaned up (such as TTL-expired cells or tombstones) is counted. + :vartype load: str + :ivar tokens: List of tokens this node covers. + :vartype tokens: list[str] + :ivar size: + :vartype size: int + :ivar host_id: The network ID of the node. + :vartype host_id: str + :ivar rack: The rack this node is part of. + :vartype rack: str + :ivar timestamp: The timestamp when these statistics were captured. + :vartype timestamp: str + :ivar disk_used_kb: The amount of disk used, in kB, of the directory /var/lib/cassandra. + :vartype disk_used_kb: int + :ivar disk_free_kb: The amount of disk free, in kB, of the directory /var/lib/cassandra. + :vartype disk_free_kb: int + :ivar memory_used_kb: Used memory (calculated as total - free - buffers - cache), in kB. + :vartype memory_used_kb: int + :ivar memory_buffers_and_cached_kb: Memory used by kernel buffers (Buffers in /proc/meminfo) + and page cache and slabs (Cached and SReclaimable in /proc/meminfo), in kB. + :vartype memory_buffers_and_cached_kb: int + :ivar memory_free_kb: Unused memory (MemFree and SwapFree in /proc/meminfo), in kB. + :vartype memory_free_kb: int + :ivar memory_total_kb: Total installed memory (MemTotal and SwapTotal in /proc/meminfo), in kB. + :vartype memory_total_kb: int + :ivar cpu_usage: A float representing the current system-wide CPU utilization as a percentage. + :vartype cpu_usage: float + :ivar is_latest_model: If node has been updated to latest model. + :vartype is_latest_model: bool + """ + + _attribute_map = { + "address": {"key": "address", "type": "str"}, + "state": {"key": "state", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "cassandra_process_status": {"key": "cassandraProcessStatus", "type": "str"}, + "load": {"key": "load", "type": "str"}, + "tokens": {"key": "tokens", "type": "[str]"}, + "size": {"key": "size", "type": "int"}, + "host_id": {"key": "hostID", "type": "str"}, + "rack": {"key": "rack", "type": "str"}, + "timestamp": {"key": "timestamp", "type": "str"}, + "disk_used_kb": {"key": "diskUsedKB", "type": "int"}, + "disk_free_kb": {"key": "diskFreeKB", "type": "int"}, + "memory_used_kb": {"key": "memoryUsedKB", "type": "int"}, + "memory_buffers_and_cached_kb": {"key": "memoryBuffersAndCachedKB", "type": "int"}, + "memory_free_kb": {"key": "memoryFreeKB", "type": "int"}, + "memory_total_kb": {"key": "memoryTotalKB", "type": "int"}, + "cpu_usage": {"key": "cpuUsage", "type": "float"}, + "is_latest_model": {"key": "isLatestModel", "type": "bool"}, + } + + def __init__( + self, + *, + address: Optional[str] = None, + state: Optional[Union[str, "_models.NodeState"]] = None, + status: Optional[str] = None, + cassandra_process_status: Optional[str] = None, + load: Optional[str] = None, + tokens: Optional[List[str]] = None, + size: Optional[int] = None, + host_id: Optional[str] = None, + rack: Optional[str] = None, + timestamp: Optional[str] = None, + disk_used_kb: Optional[int] = None, + disk_free_kb: Optional[int] = None, + memory_used_kb: Optional[int] = None, + memory_buffers_and_cached_kb: Optional[int] = None, + memory_free_kb: Optional[int] = None, + memory_total_kb: Optional[int] = None, + cpu_usage: Optional[float] = None, + is_latest_model: Optional[bool] = None, + **kwargs: Any + ) -> None: + """ + :keyword address: The node's IP address. + :paramtype address: str + :keyword state: The state of the node in Cassandra ring. Known values are: "Normal", "Leaving", + "Joining", "Moving", and "Stopped". + :paramtype state: str or ~azure.mgmt.cosmosdb.models.NodeState + :keyword status: + :paramtype status: str + :keyword cassandra_process_status: Cassandra service status on this node. + :paramtype cassandra_process_status: str + :keyword load: The amount of file system data in the data directory (e.g., 47.66 kB), excluding + all content in the snapshots subdirectories. Because all SSTable data files are included, any + data that is not cleaned up (such as TTL-expired cells or tombstones) is counted. + :paramtype load: str + :keyword tokens: List of tokens this node covers. + :paramtype tokens: list[str] + :keyword size: + :paramtype size: int + :keyword host_id: The network ID of the node. + :paramtype host_id: str + :keyword rack: The rack this node is part of. + :paramtype rack: str + :keyword timestamp: The timestamp when these statistics were captured. + :paramtype timestamp: str + :keyword disk_used_kb: The amount of disk used, in kB, of the directory /var/lib/cassandra. + :paramtype disk_used_kb: int + :keyword disk_free_kb: The amount of disk free, in kB, of the directory /var/lib/cassandra. + :paramtype disk_free_kb: int + :keyword memory_used_kb: Used memory (calculated as total - free - buffers - cache), in kB. + :paramtype memory_used_kb: int + :keyword memory_buffers_and_cached_kb: Memory used by kernel buffers (Buffers in /proc/meminfo) + and page cache and slabs (Cached and SReclaimable in /proc/meminfo), in kB. + :paramtype memory_buffers_and_cached_kb: int + :keyword memory_free_kb: Unused memory (MemFree and SwapFree in /proc/meminfo), in kB. + :paramtype memory_free_kb: int + :keyword memory_total_kb: Total installed memory (MemTotal and SwapTotal in /proc/meminfo), in + kB. + :paramtype memory_total_kb: int + :keyword cpu_usage: A float representing the current system-wide CPU utilization as a + percentage. + :paramtype cpu_usage: float + :keyword is_latest_model: If node has been updated to latest model. + :paramtype is_latest_model: bool + """ + super().__init__(**kwargs) + self.address = address + self.state = state + self.status = status + self.cassandra_process_status = cassandra_process_status + self.load = load + self.tokens = tokens + self.size = size + self.host_id = host_id + self.rack = rack + self.timestamp = timestamp + self.disk_used_kb = disk_used_kb + self.disk_free_kb = disk_free_kb + self.memory_used_kb = memory_used_kb + self.memory_buffers_and_cached_kb = memory_buffers_and_cached_kb + self.memory_free_kb = memory_free_kb + self.memory_total_kb = memory_total_kb + self.cpu_usage = cpu_usage + self.is_latest_model = is_latest_model + + +class CassandraClusterPublicStatus(_serialization.Model): + """Properties of a managed Cassandra cluster public status. + + :ivar e_tag: + :vartype e_tag: str + :ivar reaper_status: + :vartype reaper_status: ~azure.mgmt.cosmosdb.models.ManagedCassandraReaperStatus + :ivar connection_errors: List relevant information about any connection errors to the + Datacenters. + :vartype connection_errors: list[~azure.mgmt.cosmosdb.models.ConnectionError] + :ivar errors: List relevant information about any errors about cluster, data center and + connection error. + :vartype errors: list[~azure.mgmt.cosmosdb.models.CassandraError] + :ivar data_centers: List of the status of each datacenter in this cluster. + :vartype data_centers: + list[~azure.mgmt.cosmosdb.models.CassandraClusterPublicStatusDataCentersItem] + """ + + _attribute_map = { + "e_tag": {"key": "eTag", "type": "str"}, + "reaper_status": {"key": "reaperStatus", "type": "ManagedCassandraReaperStatus"}, + "connection_errors": {"key": "connectionErrors", "type": "[ConnectionError]"}, + "errors": {"key": "errors", "type": "[CassandraError]"}, + "data_centers": {"key": "dataCenters", "type": "[CassandraClusterPublicStatusDataCentersItem]"}, + } + + def __init__( + self, + *, + e_tag: Optional[str] = None, + reaper_status: Optional["_models.ManagedCassandraReaperStatus"] = None, + connection_errors: Optional[List["_models.ConnectionError"]] = None, + errors: Optional[List["_models.CassandraError"]] = None, + data_centers: Optional[List["_models.CassandraClusterPublicStatusDataCentersItem"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword e_tag: + :paramtype e_tag: str + :keyword reaper_status: + :paramtype reaper_status: ~azure.mgmt.cosmosdb.models.ManagedCassandraReaperStatus + :keyword connection_errors: List relevant information about any connection errors to the + Datacenters. + :paramtype connection_errors: list[~azure.mgmt.cosmosdb.models.ConnectionError] + :keyword errors: List relevant information about any errors about cluster, data center and + connection error. + :paramtype errors: list[~azure.mgmt.cosmosdb.models.CassandraError] + :keyword data_centers: List of the status of each datacenter in this cluster. + :paramtype data_centers: + list[~azure.mgmt.cosmosdb.models.CassandraClusterPublicStatusDataCentersItem] + """ + super().__init__(**kwargs) + self.e_tag = e_tag + self.reaper_status = reaper_status + self.connection_errors = connection_errors + self.errors = errors + self.data_centers = data_centers + + +class CassandraClusterPublicStatusDataCentersItem(_serialization.Model): # pylint: disable=name-too-long + """CassandraClusterPublicStatusDataCentersItem. + + :ivar name: The name of this Datacenter. + :vartype name: str + :ivar seed_nodes: A list of all seed nodes in the cluster, managed and unmanaged. + :vartype seed_nodes: list[str] + :ivar nodes: + :vartype nodes: list[~azure.mgmt.cosmosdb.models.CassandraClusterDataCenterNodeItem] + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "seed_nodes": {"key": "seedNodes", "type": "[str]"}, + "nodes": {"key": "nodes", "type": "[CassandraClusterDataCenterNodeItem]"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + seed_nodes: Optional[List[str]] = None, + nodes: Optional[List["_models.CassandraClusterDataCenterNodeItem"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: The name of this Datacenter. + :paramtype name: str + :keyword seed_nodes: A list of all seed nodes in the cluster, managed and unmanaged. + :paramtype seed_nodes: list[str] + :keyword nodes: + :paramtype nodes: list[~azure.mgmt.cosmosdb.models.CassandraClusterDataCenterNodeItem] + """ + super().__init__(**kwargs) + self.name = name + self.seed_nodes = seed_nodes + self.nodes = nodes + + +class CassandraError(_serialization.Model): + """CassandraError. + + :ivar code: The code of error that occurred. + :vartype code: str + :ivar message: The message of the error. + :vartype message: str + :ivar target: The target resource of the error. + :vartype target: str + :ivar additional_error_info: Additional information about the error. + :vartype additional_error_info: str + """ + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "additional_error_info": {"key": "additionalErrorInfo", "type": "str"}, + } + + def __init__( + self, + *, + code: Optional[str] = None, + message: Optional[str] = None, + target: Optional[str] = None, + additional_error_info: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword code: The code of error that occurred. + :paramtype code: str + :keyword message: The message of the error. + :paramtype message: str + :keyword target: The target resource of the error. + :paramtype target: str + :keyword additional_error_info: Additional information about the error. + :paramtype additional_error_info: str + """ + super().__init__(**kwargs) + self.code = code + self.message = message + self.target = target + self.additional_error_info = additional_error_info + + +class CassandraKeyspaceCreateUpdateParameters(ARMResourceProperties): + """Parameters to create and update Cosmos DB Cassandra keyspace. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: The standard JSON format of a Cassandra keyspace. Required. + :vartype resource: ~azure.mgmt.cosmosdb.models.CassandraKeyspaceResource + :ivar options: A key-value pair of options to be applied for the request. This corresponds to + the headers sent with the request. + :vartype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "resource": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "CassandraKeyspaceResource"}, + "options": {"key": "properties.options", "type": "CreateUpdateOptions"}, + } + + def __init__( + self, + *, + resource: "_models.CassandraKeyspaceResource", + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + options: Optional["_models.CreateUpdateOptions"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: The standard JSON format of a Cassandra keyspace. Required. + :paramtype resource: ~azure.mgmt.cosmosdb.models.CassandraKeyspaceResource + :keyword options: A key-value pair of options to be applied for the request. This corresponds + to the headers sent with the request. + :paramtype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + self.options = options + + +class OptionsResource(_serialization.Model): + """Cosmos DB options resource object. + + :ivar throughput: Value of the Cosmos DB resource throughput or autoscaleSettings. Use the + ThroughputSetting resource when retrieving offer details. + :vartype throughput: int + :ivar autoscale_settings: Specifies the Autoscale settings. + :vartype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettings + """ + + _attribute_map = { + "throughput": {"key": "throughput", "type": "int"}, + "autoscale_settings": {"key": "autoscaleSettings", "type": "AutoscaleSettings"}, + } + + def __init__( + self, + *, + throughput: Optional[int] = None, + autoscale_settings: Optional["_models.AutoscaleSettings"] = None, + **kwargs: Any + ) -> None: + """ + :keyword throughput: Value of the Cosmos DB resource throughput or autoscaleSettings. Use the + ThroughputSetting resource when retrieving offer details. + :paramtype throughput: int + :keyword autoscale_settings: Specifies the Autoscale settings. + :paramtype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettings + """ + super().__init__(**kwargs) + self.throughput = throughput + self.autoscale_settings = autoscale_settings + + +class CassandraKeyspaceGetPropertiesOptions(OptionsResource): + """CassandraKeyspaceGetPropertiesOptions. + + :ivar throughput: Value of the Cosmos DB resource throughput or autoscaleSettings. Use the + ThroughputSetting resource when retrieving offer details. + :vartype throughput: int + :ivar autoscale_settings: Specifies the Autoscale settings. + :vartype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettings + """ + + +class ExtendedResourceProperties(_serialization.Model): + """The system generated resource properties associated with SQL databases, SQL containers, Gremlin + databases and Gremlin graphs. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar rid: A system generated property. A unique identifier. + :vartype rid: str + :ivar ts: A system generated property that denotes the last updated timestamp of the resource. + :vartype ts: float + :ivar etag: A system generated property representing the resource etag required for optimistic + concurrency control. + :vartype etag: str + """ + + _validation = { + "rid": {"readonly": True}, + "ts": {"readonly": True}, + "etag": {"readonly": True}, + } + + _attribute_map = { + "rid": {"key": "_rid", "type": "str"}, + "ts": {"key": "_ts", "type": "float"}, + "etag": {"key": "_etag", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.rid = None + self.ts = None + self.etag = None + + +class CassandraKeyspaceResource(_serialization.Model): + """Cosmos DB Cassandra keyspace resource object. + + All required parameters must be populated in order to send to server. + + :ivar id: Name of the Cosmos DB Cassandra keyspace. Required. + :vartype id: str + """ + + _validation = { + "id": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + } + + def __init__(self, *, id: str, **kwargs: Any) -> None: # pylint: disable=redefined-builtin + """ + :keyword id: Name of the Cosmos DB Cassandra keyspace. Required. + :paramtype id: str + """ + super().__init__(**kwargs) + self.id = id + + +class CassandraKeyspaceGetPropertiesResource(CassandraKeyspaceResource, ExtendedResourceProperties): + """CassandraKeyspaceGetPropertiesResource. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar rid: A system generated property. A unique identifier. + :vartype rid: str + :ivar ts: A system generated property that denotes the last updated timestamp of the resource. + :vartype ts: float + :ivar etag: A system generated property representing the resource etag required for optimistic + concurrency control. + :vartype etag: str + :ivar id: Name of the Cosmos DB Cassandra keyspace. Required. + :vartype id: str + """ + + _validation = { + "rid": {"readonly": True}, + "ts": {"readonly": True}, + "etag": {"readonly": True}, + "id": {"required": True}, + } + + _attribute_map = { + "rid": {"key": "_rid", "type": "str"}, + "ts": {"key": "_ts", "type": "float"}, + "etag": {"key": "_etag", "type": "str"}, + "id": {"key": "id", "type": "str"}, + } + + def __init__(self, *, id: str, **kwargs: Any) -> None: # pylint: disable=redefined-builtin + """ + :keyword id: Name of the Cosmos DB Cassandra keyspace. Required. + :paramtype id: str + """ + super().__init__(id=id, **kwargs) + self.rid = None + self.ts = None + self.etag = None + self.id = id + + +class CassandraKeyspaceGetResults(ARMResourceProperties): + """An Azure Cosmos DB Cassandra keyspace. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: + :vartype resource: ~azure.mgmt.cosmosdb.models.CassandraKeyspaceGetPropertiesResource + :ivar options: + :vartype options: ~azure.mgmt.cosmosdb.models.CassandraKeyspaceGetPropertiesOptions + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "CassandraKeyspaceGetPropertiesResource"}, + "options": {"key": "properties.options", "type": "CassandraKeyspaceGetPropertiesOptions"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + resource: Optional["_models.CassandraKeyspaceGetPropertiesResource"] = None, + options: Optional["_models.CassandraKeyspaceGetPropertiesOptions"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: + :paramtype resource: ~azure.mgmt.cosmosdb.models.CassandraKeyspaceGetPropertiesResource + :keyword options: + :paramtype options: ~azure.mgmt.cosmosdb.models.CassandraKeyspaceGetPropertiesOptions + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + self.options = options + + +class CassandraKeyspaceListResult(_serialization.Model): + """The List operation response, that contains the Cassandra keyspaces and their properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of Cassandra keyspaces and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.CassandraKeyspaceGetResults] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[CassandraKeyspaceGetResults]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class CassandraPartitionKey(_serialization.Model): + """Cosmos DB Cassandra table partition key. + + :ivar name: Name of the Cosmos DB Cassandra table partition key. + :vartype name: str + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + } + + def __init__(self, *, name: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword name: Name of the Cosmos DB Cassandra table partition key. + :paramtype name: str + """ + super().__init__(**kwargs) + self.name = name + + +class CassandraSchema(_serialization.Model): + """Cosmos DB Cassandra table schema. + + :ivar columns: List of Cassandra table columns. + :vartype columns: list[~azure.mgmt.cosmosdb.models.Column] + :ivar partition_keys: List of partition key. + :vartype partition_keys: list[~azure.mgmt.cosmosdb.models.CassandraPartitionKey] + :ivar cluster_keys: List of cluster key. + :vartype cluster_keys: list[~azure.mgmt.cosmosdb.models.ClusterKey] + """ + + _attribute_map = { + "columns": {"key": "columns", "type": "[Column]"}, + "partition_keys": {"key": "partitionKeys", "type": "[CassandraPartitionKey]"}, + "cluster_keys": {"key": "clusterKeys", "type": "[ClusterKey]"}, + } + + def __init__( + self, + *, + columns: Optional[List["_models.Column"]] = None, + partition_keys: Optional[List["_models.CassandraPartitionKey"]] = None, + cluster_keys: Optional[List["_models.ClusterKey"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword columns: List of Cassandra table columns. + :paramtype columns: list[~azure.mgmt.cosmosdb.models.Column] + :keyword partition_keys: List of partition key. + :paramtype partition_keys: list[~azure.mgmt.cosmosdb.models.CassandraPartitionKey] + :keyword cluster_keys: List of cluster key. + :paramtype cluster_keys: list[~azure.mgmt.cosmosdb.models.ClusterKey] + """ + super().__init__(**kwargs) + self.columns = columns + self.partition_keys = partition_keys + self.cluster_keys = cluster_keys + + +class CassandraTableCreateUpdateParameters(ARMResourceProperties): + """Parameters to create and update Cosmos DB Cassandra table. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: The standard JSON format of a Cassandra table. Required. + :vartype resource: ~azure.mgmt.cosmosdb.models.CassandraTableResource + :ivar options: A key-value pair of options to be applied for the request. This corresponds to + the headers sent with the request. + :vartype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "resource": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "CassandraTableResource"}, + "options": {"key": "properties.options", "type": "CreateUpdateOptions"}, + } + + def __init__( + self, + *, + resource: "_models.CassandraTableResource", + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + options: Optional["_models.CreateUpdateOptions"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: The standard JSON format of a Cassandra table. Required. + :paramtype resource: ~azure.mgmt.cosmosdb.models.CassandraTableResource + :keyword options: A key-value pair of options to be applied for the request. This corresponds + to the headers sent with the request. + :paramtype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + self.options = options + + +class CassandraTableGetPropertiesOptions(OptionsResource): + """CassandraTableGetPropertiesOptions. + + :ivar throughput: Value of the Cosmos DB resource throughput or autoscaleSettings. Use the + ThroughputSetting resource when retrieving offer details. + :vartype throughput: int + :ivar autoscale_settings: Specifies the Autoscale settings. + :vartype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettings + """ + + +class CassandraTableResource(_serialization.Model): + """Cosmos DB Cassandra table resource object. + + All required parameters must be populated in order to send to server. + + :ivar id: Name of the Cosmos DB Cassandra table. Required. + :vartype id: str + :ivar default_ttl: Time to live of the Cosmos DB Cassandra table. + :vartype default_ttl: int + :ivar schema: Schema of the Cosmos DB Cassandra table. + :vartype schema: ~azure.mgmt.cosmosdb.models.CassandraSchema + :ivar analytical_storage_ttl: Analytical TTL. + :vartype analytical_storage_ttl: int + """ + + _validation = { + "id": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "default_ttl": {"key": "defaultTtl", "type": "int"}, + "schema": {"key": "schema", "type": "CassandraSchema"}, + "analytical_storage_ttl": {"key": "analyticalStorageTtl", "type": "int"}, + } + + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + default_ttl: Optional[int] = None, + schema: Optional["_models.CassandraSchema"] = None, + analytical_storage_ttl: Optional[int] = None, + **kwargs: Any + ) -> None: + """ + :keyword id: Name of the Cosmos DB Cassandra table. Required. + :paramtype id: str + :keyword default_ttl: Time to live of the Cosmos DB Cassandra table. + :paramtype default_ttl: int + :keyword schema: Schema of the Cosmos DB Cassandra table. + :paramtype schema: ~azure.mgmt.cosmosdb.models.CassandraSchema + :keyword analytical_storage_ttl: Analytical TTL. + :paramtype analytical_storage_ttl: int + """ + super().__init__(**kwargs) + self.id = id + self.default_ttl = default_ttl + self.schema = schema + self.analytical_storage_ttl = analytical_storage_ttl + + +class CassandraTableGetPropertiesResource(CassandraTableResource, ExtendedResourceProperties): + """CassandraTableGetPropertiesResource. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar rid: A system generated property. A unique identifier. + :vartype rid: str + :ivar ts: A system generated property that denotes the last updated timestamp of the resource. + :vartype ts: float + :ivar etag: A system generated property representing the resource etag required for optimistic + concurrency control. + :vartype etag: str + :ivar id: Name of the Cosmos DB Cassandra table. Required. + :vartype id: str + :ivar default_ttl: Time to live of the Cosmos DB Cassandra table. + :vartype default_ttl: int + :ivar schema: Schema of the Cosmos DB Cassandra table. + :vartype schema: ~azure.mgmt.cosmosdb.models.CassandraSchema + :ivar analytical_storage_ttl: Analytical TTL. + :vartype analytical_storage_ttl: int + """ + + _validation = { + "rid": {"readonly": True}, + "ts": {"readonly": True}, + "etag": {"readonly": True}, + "id": {"required": True}, + } + + _attribute_map = { + "rid": {"key": "_rid", "type": "str"}, + "ts": {"key": "_ts", "type": "float"}, + "etag": {"key": "_etag", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "default_ttl": {"key": "defaultTtl", "type": "int"}, + "schema": {"key": "schema", "type": "CassandraSchema"}, + "analytical_storage_ttl": {"key": "analyticalStorageTtl", "type": "int"}, + } + + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + default_ttl: Optional[int] = None, + schema: Optional["_models.CassandraSchema"] = None, + analytical_storage_ttl: Optional[int] = None, + **kwargs: Any + ) -> None: + """ + :keyword id: Name of the Cosmos DB Cassandra table. Required. + :paramtype id: str + :keyword default_ttl: Time to live of the Cosmos DB Cassandra table. + :paramtype default_ttl: int + :keyword schema: Schema of the Cosmos DB Cassandra table. + :paramtype schema: ~azure.mgmt.cosmosdb.models.CassandraSchema + :keyword analytical_storage_ttl: Analytical TTL. + :paramtype analytical_storage_ttl: int + """ + super().__init__( + id=id, default_ttl=default_ttl, schema=schema, analytical_storage_ttl=analytical_storage_ttl, **kwargs + ) + self.rid = None + self.ts = None + self.etag = None + self.id = id + self.default_ttl = default_ttl + self.schema = schema + self.analytical_storage_ttl = analytical_storage_ttl + + +class CassandraTableGetResults(ARMResourceProperties): + """An Azure Cosmos DB Cassandra table. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: + :vartype resource: ~azure.mgmt.cosmosdb.models.CassandraTableGetPropertiesResource + :ivar options: + :vartype options: ~azure.mgmt.cosmosdb.models.CassandraTableGetPropertiesOptions + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "CassandraTableGetPropertiesResource"}, + "options": {"key": "properties.options", "type": "CassandraTableGetPropertiesOptions"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + resource: Optional["_models.CassandraTableGetPropertiesResource"] = None, + options: Optional["_models.CassandraTableGetPropertiesOptions"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: + :paramtype resource: ~azure.mgmt.cosmosdb.models.CassandraTableGetPropertiesResource + :keyword options: + :paramtype options: ~azure.mgmt.cosmosdb.models.CassandraTableGetPropertiesOptions + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + self.options = options + + +class CassandraTableListResult(_serialization.Model): + """The List operation response, that contains the Cassandra tables and their properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of Cassandra tables and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.CassandraTableGetResults] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[CassandraTableGetResults]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class CassandraViewCreateUpdateParameters(ARMResourceProperties): + """Parameters to create and update Cosmos DB Cassandra view. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: The standard JSON format of a Cassandra view. Required. + :vartype resource: ~azure.mgmt.cosmosdb.models.CassandraViewResource + :ivar options: A key-value pair of options to be applied for the request. This corresponds to + the headers sent with the request. + :vartype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "resource": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "CassandraViewResource"}, + "options": {"key": "properties.options", "type": "CreateUpdateOptions"}, + } + + def __init__( + self, + *, + resource: "_models.CassandraViewResource", + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + options: Optional["_models.CreateUpdateOptions"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: The standard JSON format of a Cassandra view. Required. + :paramtype resource: ~azure.mgmt.cosmosdb.models.CassandraViewResource + :keyword options: A key-value pair of options to be applied for the request. This corresponds + to the headers sent with the request. + :paramtype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + self.options = options + + +class CassandraViewGetPropertiesOptions(OptionsResource): + """CassandraViewGetPropertiesOptions. + + :ivar throughput: Value of the Cosmos DB resource throughput or autoscaleSettings. Use the + ThroughputSetting resource when retrieving offer details. + :vartype throughput: int + :ivar autoscale_settings: Specifies the Autoscale settings. + :vartype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettings + """ + + +class CassandraViewResource(_serialization.Model): + """Cosmos DB Cassandra view resource object. + + All required parameters must be populated in order to send to server. + + :ivar id: Name of the Cosmos DB Cassandra view. Required. + :vartype id: str + :ivar view_definition: View Definition of the Cosmos DB Cassandra view. Required. + :vartype view_definition: str + """ + + _validation = { + "id": {"required": True}, + "view_definition": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "view_definition": {"key": "viewDefinition", "type": "str"}, + } + + def __init__(self, *, id: str, view_definition: str, **kwargs: Any) -> None: # pylint: disable=redefined-builtin + """ + :keyword id: Name of the Cosmos DB Cassandra view. Required. + :paramtype id: str + :keyword view_definition: View Definition of the Cosmos DB Cassandra view. Required. + :paramtype view_definition: str + """ + super().__init__(**kwargs) + self.id = id + self.view_definition = view_definition + + +class CassandraViewGetPropertiesResource(CassandraViewResource, ExtendedResourceProperties): + """CassandraViewGetPropertiesResource. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar rid: A system generated property. A unique identifier. + :vartype rid: str + :ivar ts: A system generated property that denotes the last updated timestamp of the resource. + :vartype ts: float + :ivar etag: A system generated property representing the resource etag required for optimistic + concurrency control. + :vartype etag: str + :ivar id: Name of the Cosmos DB Cassandra view. Required. + :vartype id: str + :ivar view_definition: View Definition of the Cosmos DB Cassandra view. Required. + :vartype view_definition: str + """ + + _validation = { + "rid": {"readonly": True}, + "ts": {"readonly": True}, + "etag": {"readonly": True}, + "id": {"required": True}, + "view_definition": {"required": True}, + } + + _attribute_map = { + "rid": {"key": "_rid", "type": "str"}, + "ts": {"key": "_ts", "type": "float"}, + "etag": {"key": "_etag", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "view_definition": {"key": "viewDefinition", "type": "str"}, + } + + def __init__(self, *, id: str, view_definition: str, **kwargs: Any) -> None: # pylint: disable=redefined-builtin + """ + :keyword id: Name of the Cosmos DB Cassandra view. Required. + :paramtype id: str + :keyword view_definition: View Definition of the Cosmos DB Cassandra view. Required. + :paramtype view_definition: str + """ + super().__init__(id=id, view_definition=view_definition, **kwargs) + self.rid = None + self.ts = None + self.etag = None + self.id = id + self.view_definition = view_definition + + +class CassandraViewGetResults(ARMResourceProperties): + """An Azure Cosmos DB Cassandra view. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: + :vartype resource: ~azure.mgmt.cosmosdb.models.CassandraViewGetPropertiesResource + :ivar options: + :vartype options: ~azure.mgmt.cosmosdb.models.CassandraViewGetPropertiesOptions + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "CassandraViewGetPropertiesResource"}, + "options": {"key": "properties.options", "type": "CassandraViewGetPropertiesOptions"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + resource: Optional["_models.CassandraViewGetPropertiesResource"] = None, + options: Optional["_models.CassandraViewGetPropertiesOptions"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: + :paramtype resource: ~azure.mgmt.cosmosdb.models.CassandraViewGetPropertiesResource + :keyword options: + :paramtype options: ~azure.mgmt.cosmosdb.models.CassandraViewGetPropertiesOptions + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + self.options = options + + +class CassandraViewListResult(_serialization.Model): + """The List operation response, that contains the Cassandra views and their properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of Cassandra views and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.CassandraViewGetResults] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[CassandraViewGetResults]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class Certificate(_serialization.Model): + """Certificate. + + :ivar pem: PEM formatted public key. + :vartype pem: str + """ + + _attribute_map = { + "pem": {"key": "pem", "type": "str"}, + } + + def __init__(self, *, pem: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword pem: PEM formatted public key. + :paramtype pem: str + """ + super().__init__(**kwargs) + self.pem = pem + + +class ChaosFaultListResponse(_serialization.Model): + """Chaos Fault List Response. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of Chaos Faults. + :vartype value: list[~azure.mgmt.cosmosdb.models.ChaosFaultResource] + :ivar next_link: The link used to get the next page of results. + :vartype next_link: str + """ + + _validation = { + "value": {"readonly": True}, + "next_link": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[ChaosFaultResource]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + self.next_link = None + + +class Resource(_serialization.Model): + """Common fields that are returned in the response for all Azure Resource Manager resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.cosmosdb.models.SystemData + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.system_data = None + + +class ProxyResource(Resource): + """The resource model definition for a Azure Resource Manager proxy resource. It will not have + tags and a location. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.cosmosdb.models.SystemData + """ + + +class ChaosFaultResource(ProxyResource): + """A request object to enable/disable the chaos fault. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.cosmosdb.models.SystemData + :ivar action: Indicates whether what action to take for the Chaos Fault. Known values are: + "Enable" and "Disable". + :vartype action: str or ~azure.mgmt.cosmosdb.models.SupportedActions + :ivar region: Region of the account where the Chaos Fault is to be enabled/disabled. + :vartype region: str + :ivar database_name: Database name. + :vartype database_name: str + :ivar container_name: Container name. + :vartype container_name: str + :ivar provisioning_state: A provisioning state of the Chaos Fault. + :vartype provisioning_state: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + "provisioning_state": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "action": {"key": "properties.action", "type": "str"}, + "region": {"key": "properties.region", "type": "str"}, + "database_name": {"key": "properties.databaseName", "type": "str"}, + "container_name": {"key": "properties.containerName", "type": "str"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + } + + def __init__( + self, + *, + action: Optional[Union[str, "_models.SupportedActions"]] = None, + region: Optional[str] = None, + database_name: Optional[str] = None, + container_name: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword action: Indicates whether what action to take for the Chaos Fault. Known values are: + "Enable" and "Disable". + :paramtype action: str or ~azure.mgmt.cosmosdb.models.SupportedActions + :keyword region: Region of the account where the Chaos Fault is to be enabled/disabled. + :paramtype region: str + :keyword database_name: Database name. + :paramtype database_name: str + :keyword container_name: Container name. + :paramtype container_name: str + """ + super().__init__(**kwargs) + self.action = action + self.region = region + self.database_name = database_name + self.container_name = container_name + self.provisioning_state = None + + +class ClientEncryptionIncludedPath(_serialization.Model): + """. + + All required parameters must be populated in order to send to server. + + :ivar path: Path that needs to be encrypted. Required. + :vartype path: str + :ivar client_encryption_key_id: The identifier of the Client Encryption Key to be used to + encrypt the path. Required. + :vartype client_encryption_key_id: str + :ivar encryption_type: The type of encryption to be performed. Eg - Deterministic, Randomized. + Required. + :vartype encryption_type: str + :ivar encryption_algorithm: The encryption algorithm which will be used. Eg - + AEAD_AES_256_CBC_HMAC_SHA256. Required. + :vartype encryption_algorithm: str + """ + + _validation = { + "path": {"required": True}, + "client_encryption_key_id": {"required": True}, + "encryption_type": {"required": True}, + "encryption_algorithm": {"required": True}, + } + + _attribute_map = { + "path": {"key": "path", "type": "str"}, + "client_encryption_key_id": {"key": "clientEncryptionKeyId", "type": "str"}, + "encryption_type": {"key": "encryptionType", "type": "str"}, + "encryption_algorithm": {"key": "encryptionAlgorithm", "type": "str"}, + } + + def __init__( + self, + *, + path: str, + client_encryption_key_id: str, + encryption_type: str, + encryption_algorithm: str, + **kwargs: Any + ) -> None: + """ + :keyword path: Path that needs to be encrypted. Required. + :paramtype path: str + :keyword client_encryption_key_id: The identifier of the Client Encryption Key to be used to + encrypt the path. Required. + :paramtype client_encryption_key_id: str + :keyword encryption_type: The type of encryption to be performed. Eg - Deterministic, + Randomized. Required. + :paramtype encryption_type: str + :keyword encryption_algorithm: The encryption algorithm which will be used. Eg - + AEAD_AES_256_CBC_HMAC_SHA256. Required. + :paramtype encryption_algorithm: str + """ + super().__init__(**kwargs) + self.path = path + self.client_encryption_key_id = client_encryption_key_id + self.encryption_type = encryption_type + self.encryption_algorithm = encryption_algorithm + + +class ClientEncryptionKeyCreateUpdateParameters(_serialization.Model): # pylint: disable=name-too-long + """Parameters to create and update ClientEncryptionKey. + + All required parameters must be populated in order to send to server. + + :ivar resource: The standard JSON format of a ClientEncryptionKey. Required. + :vartype resource: ~azure.mgmt.cosmosdb.models.ClientEncryptionKeyResource + """ + + _validation = { + "resource": {"required": True}, + } + + _attribute_map = { + "resource": {"key": "properties.resource", "type": "ClientEncryptionKeyResource"}, + } + + def __init__(self, *, resource: "_models.ClientEncryptionKeyResource", **kwargs: Any) -> None: + """ + :keyword resource: The standard JSON format of a ClientEncryptionKey. Required. + :paramtype resource: ~azure.mgmt.cosmosdb.models.ClientEncryptionKeyResource + """ + super().__init__(**kwargs) + self.resource = resource + + +class ClientEncryptionKeyResource(_serialization.Model): + """Cosmos DB client encryption key resource object. + + :ivar id: Name of the ClientEncryptionKey. + :vartype id: str + :ivar encryption_algorithm: Encryption algorithm that will be used along with this client + encryption key to encrypt/decrypt data. + :vartype encryption_algorithm: str + :ivar wrapped_data_encryption_key: Wrapped (encrypted) form of the key represented as a byte + array. + :vartype wrapped_data_encryption_key: bytes + :ivar key_wrap_metadata: Metadata for the wrapping provider that can be used to unwrap the + wrapped client encryption key. + :vartype key_wrap_metadata: ~azure.mgmt.cosmosdb.models.KeyWrapMetadata + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "encryption_algorithm": {"key": "encryptionAlgorithm", "type": "str"}, + "wrapped_data_encryption_key": {"key": "wrappedDataEncryptionKey", "type": "bytearray"}, + "key_wrap_metadata": {"key": "keyWrapMetadata", "type": "KeyWrapMetadata"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + encryption_algorithm: Optional[str] = None, + wrapped_data_encryption_key: Optional[bytes] = None, + key_wrap_metadata: Optional["_models.KeyWrapMetadata"] = None, + **kwargs: Any + ) -> None: + """ + :keyword id: Name of the ClientEncryptionKey. + :paramtype id: str + :keyword encryption_algorithm: Encryption algorithm that will be used along with this client + encryption key to encrypt/decrypt data. + :paramtype encryption_algorithm: str + :keyword wrapped_data_encryption_key: Wrapped (encrypted) form of the key represented as a byte + array. + :paramtype wrapped_data_encryption_key: bytes + :keyword key_wrap_metadata: Metadata for the wrapping provider that can be used to unwrap the + wrapped client encryption key. + :paramtype key_wrap_metadata: ~azure.mgmt.cosmosdb.models.KeyWrapMetadata + """ + super().__init__(**kwargs) + self.id = id + self.encryption_algorithm = encryption_algorithm + self.wrapped_data_encryption_key = wrapped_data_encryption_key + self.key_wrap_metadata = key_wrap_metadata + + +class ClientEncryptionKeyGetPropertiesResource(ClientEncryptionKeyResource, ExtendedResourceProperties): + """ClientEncryptionKeyGetPropertiesResource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar rid: A system generated property. A unique identifier. + :vartype rid: str + :ivar ts: A system generated property that denotes the last updated timestamp of the resource. + :vartype ts: float + :ivar etag: A system generated property representing the resource etag required for optimistic + concurrency control. + :vartype etag: str + :ivar id: Name of the ClientEncryptionKey. + :vartype id: str + :ivar encryption_algorithm: Encryption algorithm that will be used along with this client + encryption key to encrypt/decrypt data. + :vartype encryption_algorithm: str + :ivar wrapped_data_encryption_key: Wrapped (encrypted) form of the key represented as a byte + array. + :vartype wrapped_data_encryption_key: bytes + :ivar key_wrap_metadata: Metadata for the wrapping provider that can be used to unwrap the + wrapped client encryption key. + :vartype key_wrap_metadata: ~azure.mgmt.cosmosdb.models.KeyWrapMetadata + """ + + _validation = { + "rid": {"readonly": True}, + "ts": {"readonly": True}, + "etag": {"readonly": True}, + } + + _attribute_map = { + "rid": {"key": "_rid", "type": "str"}, + "ts": {"key": "_ts", "type": "float"}, + "etag": {"key": "_etag", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "encryption_algorithm": {"key": "encryptionAlgorithm", "type": "str"}, + "wrapped_data_encryption_key": {"key": "wrappedDataEncryptionKey", "type": "bytearray"}, + "key_wrap_metadata": {"key": "keyWrapMetadata", "type": "KeyWrapMetadata"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + encryption_algorithm: Optional[str] = None, + wrapped_data_encryption_key: Optional[bytes] = None, + key_wrap_metadata: Optional["_models.KeyWrapMetadata"] = None, + **kwargs: Any + ) -> None: + """ + :keyword id: Name of the ClientEncryptionKey. + :paramtype id: str + :keyword encryption_algorithm: Encryption algorithm that will be used along with this client + encryption key to encrypt/decrypt data. + :paramtype encryption_algorithm: str + :keyword wrapped_data_encryption_key: Wrapped (encrypted) form of the key represented as a byte + array. + :paramtype wrapped_data_encryption_key: bytes + :keyword key_wrap_metadata: Metadata for the wrapping provider that can be used to unwrap the + wrapped client encryption key. + :paramtype key_wrap_metadata: ~azure.mgmt.cosmosdb.models.KeyWrapMetadata + """ + super().__init__( + id=id, + encryption_algorithm=encryption_algorithm, + wrapped_data_encryption_key=wrapped_data_encryption_key, + key_wrap_metadata=key_wrap_metadata, + **kwargs + ) + self.rid = None + self.ts = None + self.etag = None + self.id = id + self.encryption_algorithm = encryption_algorithm + self.wrapped_data_encryption_key = wrapped_data_encryption_key + self.key_wrap_metadata = key_wrap_metadata + + +class ClientEncryptionKeyGetResults(ARMProxyResource): + """Client Encryption Key. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the database account. + :vartype id: str + :ivar name: The name of the database account. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar resource: + :vartype resource: ~azure.mgmt.cosmosdb.models.ClientEncryptionKeyGetPropertiesResource + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "resource": {"key": "properties.resource", "type": "ClientEncryptionKeyGetPropertiesResource"}, + } + + def __init__( + self, *, resource: Optional["_models.ClientEncryptionKeyGetPropertiesResource"] = None, **kwargs: Any + ) -> None: + """ + :keyword resource: + :paramtype resource: ~azure.mgmt.cosmosdb.models.ClientEncryptionKeyGetPropertiesResource + """ + super().__init__(**kwargs) + self.resource = resource + + +class ClientEncryptionKeysListResult(_serialization.Model): + """The List operation response, that contains the client encryption keys and their properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of client encryption keys and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.ClientEncryptionKeyGetResults] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[ClientEncryptionKeyGetResults]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class ClientEncryptionPolicy(_serialization.Model): + """Cosmos DB client encryption policy. + + All required parameters must be populated in order to send to server. + + :ivar included_paths: Paths of the item that need encryption along with path-specific settings. + Required. + :vartype included_paths: list[~azure.mgmt.cosmosdb.models.ClientEncryptionIncludedPath] + :ivar policy_format_version: Version of the client encryption policy definition. Supported + versions are 1 and 2. Version 2 supports id and partition key path encryption. Required. + :vartype policy_format_version: int + """ + + _validation = { + "included_paths": {"required": True}, + "policy_format_version": {"required": True, "maximum": 2, "minimum": 1}, + } + + _attribute_map = { + "included_paths": {"key": "includedPaths", "type": "[ClientEncryptionIncludedPath]"}, + "policy_format_version": {"key": "policyFormatVersion", "type": "int"}, + } + + def __init__( + self, *, included_paths: List["_models.ClientEncryptionIncludedPath"], policy_format_version: int, **kwargs: Any + ) -> None: + """ + :keyword included_paths: Paths of the item that need encryption along with path-specific + settings. Required. + :paramtype included_paths: list[~azure.mgmt.cosmosdb.models.ClientEncryptionIncludedPath] + :keyword policy_format_version: Version of the client encryption policy definition. Supported + versions are 1 and 2. Version 2 supports id and partition key path encryption. Required. + :paramtype policy_format_version: int + """ + super().__init__(**kwargs) + self.included_paths = included_paths + self.policy_format_version = policy_format_version + + +class ClusterKey(_serialization.Model): + """Cosmos DB Cassandra table cluster key. + + :ivar name: Name of the Cosmos DB Cassandra table cluster key. + :vartype name: str + :ivar order_by: Order of the Cosmos DB Cassandra table cluster key, only support "Asc" and + "Desc". + :vartype order_by: str + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "order_by": {"key": "orderBy", "type": "str"}, + } + + def __init__(self, *, name: Optional[str] = None, order_by: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword name: Name of the Cosmos DB Cassandra table cluster key. + :paramtype name: str + :keyword order_by: Order of the Cosmos DB Cassandra table cluster key, only support "Asc" and + "Desc". + :paramtype order_by: str + """ + super().__init__(**kwargs) + self.name = name + self.order_by = order_by + + +class ManagedCassandraARMResourceProperties(_serialization.Model): + """The core properties of ARM resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedCassandraManagedServiceIdentity + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedCassandraManagedServiceIdentity"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedCassandraManagedServiceIdentity"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedCassandraManagedServiceIdentity + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.location = location + self.tags = tags + self.identity = identity + + +class ClusterResource(ManagedCassandraARMResourceProperties): + """Representation of a managed Cassandra cluster. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedCassandraManagedServiceIdentity + :ivar properties: Properties of a managed Cassandra cluster. + :vartype properties: ~azure.mgmt.cosmosdb.models.ClusterResourceProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedCassandraManagedServiceIdentity"}, + "properties": {"key": "properties", "type": "ClusterResourceProperties"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedCassandraManagedServiceIdentity"] = None, + properties: Optional["_models.ClusterResourceProperties"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedCassandraManagedServiceIdentity + :keyword properties: Properties of a managed Cassandra cluster. + :paramtype properties: ~azure.mgmt.cosmosdb.models.ClusterResourceProperties + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.properties = properties + + +class ClusterResourceProperties(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Properties of a managed Cassandra cluster. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar provisioning_state: The status of the resource at the time the operation was called. + Known values are: "Creating", "Updating", "Deleting", "Succeeded", "Failed", and "Canceled". + :vartype provisioning_state: str or + ~azure.mgmt.cosmosdb.models.ManagedCassandraProvisioningState + :ivar restore_from_backup_id: To create an empty cluster, omit this field or set it to null. To + restore a backup into a new cluster, set this field to the resource id of the backup. + :vartype restore_from_backup_id: str + :ivar delegated_management_subnet_id: Resource id of a subnet that this cluster's management + service should have its network interface attached to. The subnet must be routable to all + subnets that will be delegated to data centers. The resource id must be of the form + '/subscriptions/:code:``/resourceGroups/:code:``/providers/Microsoft.Network/virtualNetworks/:code:``/subnets/:code:``'. + :vartype delegated_management_subnet_id: str + :ivar cassandra_version: Which version of Cassandra should this cluster converge to running + (e.g., 3.11). When updated, the cluster may take some time to migrate to the new version. + :vartype cassandra_version: str + :ivar cluster_name_override: If you need to set the clusterName property in cassandra.yaml to + something besides the resource name of the cluster, set the value to use on this property. + :vartype cluster_name_override: str + :ivar authentication_method: Which authentication method Cassandra should use to authenticate + clients. 'None' turns off authentication, so should not be used except in emergencies. + 'Cassandra' is the default password based authentication. The default is 'Cassandra'. Known + values are: "None", "Cassandra", and "Ldap". + :vartype authentication_method: str or ~azure.mgmt.cosmosdb.models.AuthenticationMethod + :ivar initial_cassandra_admin_password: Initial password for clients connecting as admin to the + cluster. Should be changed after cluster creation. Returns null on GET. This field only applies + when the authenticationMethod field is 'Cassandra'. + :vartype initial_cassandra_admin_password: str + :ivar prometheus_endpoint: Hostname or IP address where the Prometheus endpoint containing data + about the managed Cassandra nodes can be reached. + :vartype prometheus_endpoint: ~azure.mgmt.cosmosdb.models.SeedNode + :ivar repair_enabled: Should automatic repairs run on this cluster? If omitted, this is true, + and should stay true unless you are running a hybrid cluster where you are already doing your + own repairs. + :vartype repair_enabled: bool + :ivar auto_replicate: The form of AutoReplicate that is being used by this cluster. Known + values are: "None", "SystemKeyspaces", and "AllKeyspaces". + :vartype auto_replicate: str or ~azure.mgmt.cosmosdb.models.AutoReplicate + :ivar client_certificates: List of TLS certificates used to authorize clients connecting to the + cluster. All connections are TLS encrypted whether clientCertificates is set or not, but if + clientCertificates is set, the managed Cassandra cluster will reject all connections not + bearing a TLS client certificate that can be validated from one or more of the public + certificates in this property. + :vartype client_certificates: list[~azure.mgmt.cosmosdb.models.Certificate] + :ivar external_gossip_certificates: List of TLS certificates used to authorize gossip from + unmanaged data centers. The TLS certificates of all nodes in unmanaged data centers must be + verifiable using one of the certificates provided in this property. + :vartype external_gossip_certificates: list[~azure.mgmt.cosmosdb.models.Certificate] + :ivar gossip_certificates: List of TLS certificates that unmanaged nodes must trust for gossip + with managed nodes. All managed nodes will present TLS client certificates that are verifiable + using one of the certificates provided in this property. + :vartype gossip_certificates: list[~azure.mgmt.cosmosdb.models.Certificate] + :ivar external_seed_nodes: List of IP addresses of seed nodes in unmanaged data centers. These + will be added to the seed node lists of all managed nodes. + :vartype external_seed_nodes: list[~azure.mgmt.cosmosdb.models.SeedNode] + :ivar seed_nodes: List of IP addresses of seed nodes in the managed data centers. These should + be added to the seed node lists of all unmanaged nodes. + :vartype seed_nodes: list[~azure.mgmt.cosmosdb.models.SeedNode] + :ivar external_data_centers: List of the data center names for unmanaged data centers in this + cluster to be included in auto-replication. + :vartype external_data_centers: list[str] + :ivar hours_between_backups: (Deprecated) Number of hours to wait between taking a backup of + the cluster. + :vartype hours_between_backups: int + :ivar deallocated: Whether the cluster and associated data centers has been deallocated. + :vartype deallocated: bool + :ivar cassandra_audit_logging_enabled: Whether Cassandra audit logging is enabled. + :vartype cassandra_audit_logging_enabled: bool + :ivar cluster_type: Type of the cluster. If set to Production, some operations might not be + permitted on cluster. Known values are: "Production" and "NonProduction". + :vartype cluster_type: str or ~azure.mgmt.cosmosdb.models.ClusterType + :ivar provision_error: Error related to resource provisioning. + :vartype provision_error: ~azure.mgmt.cosmosdb.models.CassandraError + :ivar extensions: Extensions to be added or updated on cluster. + :vartype extensions: list[str] + :ivar backup_schedules: List of backup schedules that define when you want to back up your + data. + :vartype backup_schedules: list[~azure.mgmt.cosmosdb.models.BackupSchedule] + :ivar scheduled_event_strategy: How the nodes in the cluster react to scheduled events. Known + values are: "Ignore", "StopAny", and "StopByRack". + :vartype scheduled_event_strategy: str or ~azure.mgmt.cosmosdb.models.ScheduledEventStrategy + :ivar azure_connection_method: How to connect to the azure services needed for running the + cluster. Known values are: "None" and "VPN". + :vartype azure_connection_method: str or ~azure.mgmt.cosmosdb.models.AzureConnectionType + :ivar private_link_resource_id: If the Connection Method is Vpn, this is the Id of the private + link resource that the datacenters need to connect to. + :vartype private_link_resource_id: str + """ + + _validation = { + "gossip_certificates": {"readonly": True}, + "seed_nodes": {"readonly": True}, + "private_link_resource_id": {"readonly": True}, + } + + _attribute_map = { + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "restore_from_backup_id": {"key": "restoreFromBackupId", "type": "str"}, + "delegated_management_subnet_id": {"key": "delegatedManagementSubnetId", "type": "str"}, + "cassandra_version": {"key": "cassandraVersion", "type": "str"}, + "cluster_name_override": {"key": "clusterNameOverride", "type": "str"}, + "authentication_method": {"key": "authenticationMethod", "type": "str"}, + "initial_cassandra_admin_password": {"key": "initialCassandraAdminPassword", "type": "str"}, + "prometheus_endpoint": {"key": "prometheusEndpoint", "type": "SeedNode"}, + "repair_enabled": {"key": "repairEnabled", "type": "bool"}, + "auto_replicate": {"key": "autoReplicate", "type": "str"}, + "client_certificates": {"key": "clientCertificates", "type": "[Certificate]"}, + "external_gossip_certificates": {"key": "externalGossipCertificates", "type": "[Certificate]"}, + "gossip_certificates": {"key": "gossipCertificates", "type": "[Certificate]"}, + "external_seed_nodes": {"key": "externalSeedNodes", "type": "[SeedNode]"}, + "seed_nodes": {"key": "seedNodes", "type": "[SeedNode]"}, + "external_data_centers": {"key": "externalDataCenters", "type": "[str]"}, + "hours_between_backups": {"key": "hoursBetweenBackups", "type": "int"}, + "deallocated": {"key": "deallocated", "type": "bool"}, + "cassandra_audit_logging_enabled": {"key": "cassandraAuditLoggingEnabled", "type": "bool"}, + "cluster_type": {"key": "clusterType", "type": "str"}, + "provision_error": {"key": "provisionError", "type": "CassandraError"}, + "extensions": {"key": "extensions", "type": "[str]"}, + "backup_schedules": {"key": "backupSchedules", "type": "[BackupSchedule]"}, + "scheduled_event_strategy": {"key": "scheduledEventStrategy", "type": "str"}, + "azure_connection_method": {"key": "azureConnectionMethod", "type": "str"}, + "private_link_resource_id": {"key": "privateLinkResourceId", "type": "str"}, + } + + def __init__( # pylint: disable=too-many-locals + self, + *, + provisioning_state: Optional[Union[str, "_models.ManagedCassandraProvisioningState"]] = None, + restore_from_backup_id: Optional[str] = None, + delegated_management_subnet_id: Optional[str] = None, + cassandra_version: Optional[str] = None, + cluster_name_override: Optional[str] = None, + authentication_method: Optional[Union[str, "_models.AuthenticationMethod"]] = None, + initial_cassandra_admin_password: Optional[str] = None, + prometheus_endpoint: Optional["_models.SeedNode"] = None, + repair_enabled: Optional[bool] = None, + auto_replicate: Optional[Union[str, "_models.AutoReplicate"]] = None, + client_certificates: Optional[List["_models.Certificate"]] = None, + external_gossip_certificates: Optional[List["_models.Certificate"]] = None, + external_seed_nodes: Optional[List["_models.SeedNode"]] = None, + external_data_centers: Optional[List[str]] = None, + hours_between_backups: Optional[int] = None, + deallocated: Optional[bool] = None, + cassandra_audit_logging_enabled: Optional[bool] = None, + cluster_type: Optional[Union[str, "_models.ClusterType"]] = None, + provision_error: Optional["_models.CassandraError"] = None, + extensions: Optional[List[str]] = None, + backup_schedules: Optional[List["_models.BackupSchedule"]] = None, + scheduled_event_strategy: Optional[Union[str, "_models.ScheduledEventStrategy"]] = None, + azure_connection_method: Optional[Union[str, "_models.AzureConnectionType"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword provisioning_state: The status of the resource at the time the operation was called. + Known values are: "Creating", "Updating", "Deleting", "Succeeded", "Failed", and "Canceled". + :paramtype provisioning_state: str or + ~azure.mgmt.cosmosdb.models.ManagedCassandraProvisioningState + :keyword restore_from_backup_id: To create an empty cluster, omit this field or set it to null. + To restore a backup into a new cluster, set this field to the resource id of the backup. + :paramtype restore_from_backup_id: str + :keyword delegated_management_subnet_id: Resource id of a subnet that this cluster's management + service should have its network interface attached to. The subnet must be routable to all + subnets that will be delegated to data centers. The resource id must be of the form + '/subscriptions/:code:``/resourceGroups/:code:``/providers/Microsoft.Network/virtualNetworks/:code:``/subnets/:code:``'. + :paramtype delegated_management_subnet_id: str + :keyword cassandra_version: Which version of Cassandra should this cluster converge to running + (e.g., 3.11). When updated, the cluster may take some time to migrate to the new version. + :paramtype cassandra_version: str + :keyword cluster_name_override: If you need to set the clusterName property in cassandra.yaml + to something besides the resource name of the cluster, set the value to use on this property. + :paramtype cluster_name_override: str + :keyword authentication_method: Which authentication method Cassandra should use to + authenticate clients. 'None' turns off authentication, so should not be used except in + emergencies. 'Cassandra' is the default password based authentication. The default is + 'Cassandra'. Known values are: "None", "Cassandra", and "Ldap". + :paramtype authentication_method: str or ~azure.mgmt.cosmosdb.models.AuthenticationMethod + :keyword initial_cassandra_admin_password: Initial password for clients connecting as admin to + the cluster. Should be changed after cluster creation. Returns null on GET. This field only + applies when the authenticationMethod field is 'Cassandra'. + :paramtype initial_cassandra_admin_password: str + :keyword prometheus_endpoint: Hostname or IP address where the Prometheus endpoint containing + data about the managed Cassandra nodes can be reached. + :paramtype prometheus_endpoint: ~azure.mgmt.cosmosdb.models.SeedNode + :keyword repair_enabled: Should automatic repairs run on this cluster? If omitted, this is + true, and should stay true unless you are running a hybrid cluster where you are already doing + your own repairs. + :paramtype repair_enabled: bool + :keyword auto_replicate: The form of AutoReplicate that is being used by this cluster. Known + values are: "None", "SystemKeyspaces", and "AllKeyspaces". + :paramtype auto_replicate: str or ~azure.mgmt.cosmosdb.models.AutoReplicate + :keyword client_certificates: List of TLS certificates used to authorize clients connecting to + the cluster. All connections are TLS encrypted whether clientCertificates is set or not, but if + clientCertificates is set, the managed Cassandra cluster will reject all connections not + bearing a TLS client certificate that can be validated from one or more of the public + certificates in this property. + :paramtype client_certificates: list[~azure.mgmt.cosmosdb.models.Certificate] + :keyword external_gossip_certificates: List of TLS certificates used to authorize gossip from + unmanaged data centers. The TLS certificates of all nodes in unmanaged data centers must be + verifiable using one of the certificates provided in this property. + :paramtype external_gossip_certificates: list[~azure.mgmt.cosmosdb.models.Certificate] + :keyword external_seed_nodes: List of IP addresses of seed nodes in unmanaged data centers. + These will be added to the seed node lists of all managed nodes. + :paramtype external_seed_nodes: list[~azure.mgmt.cosmosdb.models.SeedNode] + :keyword external_data_centers: List of the data center names for unmanaged data centers in + this cluster to be included in auto-replication. + :paramtype external_data_centers: list[str] + :keyword hours_between_backups: (Deprecated) Number of hours to wait between taking a backup of + the cluster. + :paramtype hours_between_backups: int + :keyword deallocated: Whether the cluster and associated data centers has been deallocated. + :paramtype deallocated: bool + :keyword cassandra_audit_logging_enabled: Whether Cassandra audit logging is enabled. + :paramtype cassandra_audit_logging_enabled: bool + :keyword cluster_type: Type of the cluster. If set to Production, some operations might not be + permitted on cluster. Known values are: "Production" and "NonProduction". + :paramtype cluster_type: str or ~azure.mgmt.cosmosdb.models.ClusterType + :keyword provision_error: Error related to resource provisioning. + :paramtype provision_error: ~azure.mgmt.cosmosdb.models.CassandraError + :keyword extensions: Extensions to be added or updated on cluster. + :paramtype extensions: list[str] + :keyword backup_schedules: List of backup schedules that define when you want to back up your + data. + :paramtype backup_schedules: list[~azure.mgmt.cosmosdb.models.BackupSchedule] + :keyword scheduled_event_strategy: How the nodes in the cluster react to scheduled events. + Known values are: "Ignore", "StopAny", and "StopByRack". + :paramtype scheduled_event_strategy: str or ~azure.mgmt.cosmosdb.models.ScheduledEventStrategy + :keyword azure_connection_method: How to connect to the azure services needed for running the + cluster. Known values are: "None" and "VPN". + :paramtype azure_connection_method: str or ~azure.mgmt.cosmosdb.models.AzureConnectionType + """ + super().__init__(**kwargs) + self.provisioning_state = provisioning_state + self.restore_from_backup_id = restore_from_backup_id + self.delegated_management_subnet_id = delegated_management_subnet_id + self.cassandra_version = cassandra_version + self.cluster_name_override = cluster_name_override + self.authentication_method = authentication_method + self.initial_cassandra_admin_password = initial_cassandra_admin_password + self.prometheus_endpoint = prometheus_endpoint + self.repair_enabled = repair_enabled + self.auto_replicate = auto_replicate + self.client_certificates = client_certificates + self.external_gossip_certificates = external_gossip_certificates + self.gossip_certificates = None + self.external_seed_nodes = external_seed_nodes + self.seed_nodes = None + self.external_data_centers = external_data_centers + self.hours_between_backups = hours_between_backups + self.deallocated = deallocated + self.cassandra_audit_logging_enabled = cassandra_audit_logging_enabled + self.cluster_type = cluster_type + self.provision_error = provision_error + self.extensions = extensions + self.backup_schedules = backup_schedules + self.scheduled_event_strategy = scheduled_event_strategy + self.azure_connection_method = azure_connection_method + self.private_link_resource_id = None + + +class Column(_serialization.Model): + """Cosmos DB Cassandra table column. + + :ivar name: Name of the Cosmos DB Cassandra table column. + :vartype name: str + :ivar type: Type of the Cosmos DB Cassandra table column. + :vartype type: str + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, *, name: Optional[str] = None, type: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword name: Name of the Cosmos DB Cassandra table column. + :paramtype name: str + :keyword type: Type of the Cosmos DB Cassandra table column. + :paramtype type: str + """ + super().__init__(**kwargs) + self.name = name + self.type = type + + +class CommandOutput(_serialization.Model): + """Response of /command api. + + :ivar command_output: Output of the command. + :vartype command_output: str + """ + + _attribute_map = { + "command_output": {"key": "commandOutput", "type": "str"}, + } + + def __init__(self, *, command_output: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword command_output: Output of the command. + :paramtype command_output: str + """ + super().__init__(**kwargs) + self.command_output = command_output + + +class CommandPostBody(_serialization.Model): + """Specification of which command to run where. + + All required parameters must be populated in order to send to server. + + :ivar command: The command which should be run. Required. + :vartype command: str + :ivar arguments: The arguments for the command to be run. + :vartype arguments: JSON + :ivar host: IP address of the cassandra host to run the command on. Required. + :vartype host: str + :ivar cassandra_stop_start: If true, stops cassandra before executing the command and then + start it again. + :vartype cassandra_stop_start: bool + :ivar read_write: If true, allows the command to *write* to the cassandra directory, otherwise + read-only. + :vartype read_write: bool + """ + + _validation = { + "command": {"required": True}, + "host": {"required": True}, + } + + _attribute_map = { + "command": {"key": "command", "type": "str"}, + "arguments": {"key": "arguments", "type": "object"}, + "host": {"key": "host", "type": "str"}, + "cassandra_stop_start": {"key": "cassandra-stop-start", "type": "bool"}, + "read_write": {"key": "readWrite", "type": "bool"}, + } + + def __init__( + self, + *, + command: str, + host: str, + arguments: Optional[JSON] = None, + cassandra_stop_start: Optional[bool] = None, + read_write: Optional[bool] = None, + **kwargs: Any + ) -> None: + """ + :keyword command: The command which should be run. Required. + :paramtype command: str + :keyword arguments: The arguments for the command to be run. + :paramtype arguments: JSON + :keyword host: IP address of the cassandra host to run the command on. Required. + :paramtype host: str + :keyword cassandra_stop_start: If true, stops cassandra before executing the command and then + start it again. + :paramtype cassandra_stop_start: bool + :keyword read_write: If true, allows the command to *write* to the cassandra directory, + otherwise read-only. + :paramtype read_write: bool + """ + super().__init__(**kwargs) + self.command = command + self.arguments = arguments + self.host = host + self.cassandra_stop_start = cassandra_stop_start + self.read_write = read_write + + +class CommandPublicResource(_serialization.Model): + """resource representing a command. + + :ivar command: The command which should be run. + :vartype command: str + :ivar command_id: The unique id of command. + :vartype command_id: str + :ivar arguments: The arguments for the command to be run. + :vartype arguments: JSON + :ivar host: IP address of the cassandra host to run the command on. + :vartype host: str + :ivar is_admin: Whether command has admin privileges. + :vartype is_admin: bool + :ivar cassandra_stop_start: If true, stops cassandra before executing the command and then + start it again. + :vartype cassandra_stop_start: bool + :ivar read_write: If true, allows the command to *write* to the cassandra directory, otherwise + read-only. + :vartype read_write: bool + :ivar result: Result output of the command. + :vartype result: str + :ivar status: Status of the command. Known values are: "Done", "Running", "Enqueue", + "Processing", "Finished", and "Failed". + :vartype status: str or ~azure.mgmt.cosmosdb.models.CommandStatus + :ivar output_file: The name of the file where the result is written. + :vartype output_file: str + """ + + _attribute_map = { + "command": {"key": "command", "type": "str"}, + "command_id": {"key": "commandId", "type": "str"}, + "arguments": {"key": "arguments", "type": "object"}, + "host": {"key": "host", "type": "str"}, + "is_admin": {"key": "isAdmin", "type": "bool"}, + "cassandra_stop_start": {"key": "cassandraStopStart", "type": "bool"}, + "read_write": {"key": "readWrite", "type": "bool"}, + "result": {"key": "result", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "output_file": {"key": "outputFile", "type": "str"}, + } + + def __init__( + self, + *, + command: Optional[str] = None, + command_id: Optional[str] = None, + arguments: Optional[JSON] = None, + host: Optional[str] = None, + is_admin: Optional[bool] = None, + cassandra_stop_start: Optional[bool] = None, + read_write: Optional[bool] = None, + result: Optional[str] = None, + status: Optional[Union[str, "_models.CommandStatus"]] = None, + output_file: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword command: The command which should be run. + :paramtype command: str + :keyword command_id: The unique id of command. + :paramtype command_id: str + :keyword arguments: The arguments for the command to be run. + :paramtype arguments: JSON + :keyword host: IP address of the cassandra host to run the command on. + :paramtype host: str + :keyword is_admin: Whether command has admin privileges. + :paramtype is_admin: bool + :keyword cassandra_stop_start: If true, stops cassandra before executing the command and then + start it again. + :paramtype cassandra_stop_start: bool + :keyword read_write: If true, allows the command to *write* to the cassandra directory, + otherwise read-only. + :paramtype read_write: bool + :keyword result: Result output of the command. + :paramtype result: str + :keyword status: Status of the command. Known values are: "Done", "Running", "Enqueue", + "Processing", "Finished", and "Failed". + :paramtype status: str or ~azure.mgmt.cosmosdb.models.CommandStatus + :keyword output_file: The name of the file where the result is written. + :paramtype output_file: str + """ + super().__init__(**kwargs) + self.command = command + self.command_id = command_id + self.arguments = arguments + self.host = host + self.is_admin = is_admin + self.cassandra_stop_start = cassandra_stop_start + self.read_write = read_write + self.result = result + self.status = status + self.output_file = output_file + + +class CompositePath(_serialization.Model): + """CompositePath. + + :ivar path: The path for which the indexing behavior applies to. Index paths typically start + with root and end with wildcard (/path/*). + :vartype path: str + :ivar order: Sort order for composite paths. Known values are: "ascending" and "descending". + :vartype order: str or ~azure.mgmt.cosmosdb.models.CompositePathSortOrder + """ + + _attribute_map = { + "path": {"key": "path", "type": "str"}, + "order": {"key": "order", "type": "str"}, + } + + def __init__( + self, + *, + path: Optional[str] = None, + order: Optional[Union[str, "_models.CompositePathSortOrder"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword path: The path for which the indexing behavior applies to. Index paths typically start + with root and end with wildcard (/path/*). + :paramtype path: str + :keyword order: Sort order for composite paths. Known values are: "ascending" and "descending". + :paramtype order: str or ~azure.mgmt.cosmosdb.models.CompositePathSortOrder + """ + super().__init__(**kwargs) + self.path = path + self.order = order + + +class ComputedProperty(_serialization.Model): + """The definition of a computed property. + + :ivar name: The name of a computed property, for example - "cp_lowerName". + :vartype name: str + :ivar query: The query that evaluates the value for computed property, for example - "SELECT + VALUE LOWER(c.name) FROM c". + :vartype query: str + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "query": {"key": "query", "type": "str"}, + } + + def __init__(self, *, name: Optional[str] = None, query: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword name: The name of a computed property, for example - "cp_lowerName". + :paramtype name: str + :keyword query: The query that evaluates the value for computed property, for example - "SELECT + VALUE LOWER(c.name) FROM c". + :paramtype query: str + """ + super().__init__(**kwargs) + self.name = name + self.query = query + + +class ConflictResolutionPolicy(_serialization.Model): + """The conflict resolution policy for the container. + + :ivar mode: Indicates the conflict resolution mode. Known values are: "LastWriterWins" and + "Custom". + :vartype mode: str or ~azure.mgmt.cosmosdb.models.ConflictResolutionMode + :ivar conflict_resolution_path: The conflict resolution path in the case of LastWriterWins + mode. + :vartype conflict_resolution_path: str + :ivar conflict_resolution_procedure: The procedure to resolve conflicts in the case of custom + mode. + :vartype conflict_resolution_procedure: str + """ + + _attribute_map = { + "mode": {"key": "mode", "type": "str"}, + "conflict_resolution_path": {"key": "conflictResolutionPath", "type": "str"}, + "conflict_resolution_procedure": {"key": "conflictResolutionProcedure", "type": "str"}, + } + + def __init__( + self, + *, + mode: Union[str, "_models.ConflictResolutionMode"] = "LastWriterWins", + conflict_resolution_path: Optional[str] = None, + conflict_resolution_procedure: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword mode: Indicates the conflict resolution mode. Known values are: "LastWriterWins" and + "Custom". + :paramtype mode: str or ~azure.mgmt.cosmosdb.models.ConflictResolutionMode + :keyword conflict_resolution_path: The conflict resolution path in the case of LastWriterWins + mode. + :paramtype conflict_resolution_path: str + :keyword conflict_resolution_procedure: The procedure to resolve conflicts in the case of + custom mode. + :paramtype conflict_resolution_procedure: str + """ + super().__init__(**kwargs) + self.mode = mode + self.conflict_resolution_path = conflict_resolution_path + self.conflict_resolution_procedure = conflict_resolution_procedure + + +class ConnectionError(_serialization.Model): + """ConnectionError. + + :ivar connection_state: The kind of connection error that occurred. Known values are: + "Unknown", "OK", "OperatorToDataCenterNetworkError", "DatacenterToDatacenterNetworkError", + "InternalOperatorToDataCenterCertificateError", and "InternalError". + :vartype connection_state: str or ~azure.mgmt.cosmosdb.models.ConnectionState + :ivar i_p_from: The IP of host that originated the failed connection. + :vartype i_p_from: str + :ivar i_p_to: The IP that the connection attempted to reach. + :vartype i_p_to: str + :ivar port: The TCP port the connection was attempted on. + :vartype port: int + :ivar exception: Detailed error message about the failed connection. + :vartype exception: str + """ + + _attribute_map = { + "connection_state": {"key": "connectionState", "type": "str"}, + "i_p_from": {"key": "iPFrom", "type": "str"}, + "i_p_to": {"key": "iPTo", "type": "str"}, + "port": {"key": "port", "type": "int"}, + "exception": {"key": "exception", "type": "str"}, + } + + def __init__( + self, + *, + connection_state: Optional[Union[str, "_models.ConnectionState"]] = None, + i_p_from: Optional[str] = None, + i_p_to: Optional[str] = None, + port: Optional[int] = None, + exception: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword connection_state: The kind of connection error that occurred. Known values are: + "Unknown", "OK", "OperatorToDataCenterNetworkError", "DatacenterToDatacenterNetworkError", + "InternalOperatorToDataCenterCertificateError", and "InternalError". + :paramtype connection_state: str or ~azure.mgmt.cosmosdb.models.ConnectionState + :keyword i_p_from: The IP of host that originated the failed connection. + :paramtype i_p_from: str + :keyword i_p_to: The IP that the connection attempted to reach. + :paramtype i_p_to: str + :keyword port: The TCP port the connection was attempted on. + :paramtype port: int + :keyword exception: Detailed error message about the failed connection. + :paramtype exception: str + """ + super().__init__(**kwargs) + self.connection_state = connection_state + self.i_p_from = i_p_from + self.i_p_to = i_p_to + self.port = port + self.exception = exception + + +class ConsistencyPolicy(_serialization.Model): + """The consistency policy for the Cosmos DB database account. + + All required parameters must be populated in order to send to server. + + :ivar default_consistency_level: The default consistency level and configuration settings of + the Cosmos DB account. Required. Known values are: "Eventual", "Session", "BoundedStaleness", + "Strong", and "ConsistentPrefix". + :vartype default_consistency_level: str or ~azure.mgmt.cosmosdb.models.DefaultConsistencyLevel + :ivar max_staleness_prefix: When used with the Bounded Staleness consistency level, this value + represents the number of stale requests tolerated. Accepted range for this value is 1 – + 2,147,483,647. Required when defaultConsistencyPolicy is set to 'BoundedStaleness'. + :vartype max_staleness_prefix: int + :ivar max_interval_in_seconds: When used with the Bounded Staleness consistency level, this + value represents the time amount of staleness (in seconds) tolerated. Accepted range for this + value is 5 - 86400. Required when defaultConsistencyPolicy is set to 'BoundedStaleness'. + :vartype max_interval_in_seconds: int + """ + + _validation = { + "default_consistency_level": {"required": True}, + "max_staleness_prefix": {"maximum": 2147483647, "minimum": 1}, + "max_interval_in_seconds": {"maximum": 86400, "minimum": 5}, + } + + _attribute_map = { + "default_consistency_level": {"key": "defaultConsistencyLevel", "type": "str"}, + "max_staleness_prefix": {"key": "maxStalenessPrefix", "type": "int"}, + "max_interval_in_seconds": {"key": "maxIntervalInSeconds", "type": "int"}, + } + + def __init__( + self, + *, + default_consistency_level: Union[str, "_models.DefaultConsistencyLevel"], + max_staleness_prefix: Optional[int] = None, + max_interval_in_seconds: Optional[int] = None, + **kwargs: Any + ) -> None: + """ + :keyword default_consistency_level: The default consistency level and configuration settings of + the Cosmos DB account. Required. Known values are: "Eventual", "Session", "BoundedStaleness", + "Strong", and "ConsistentPrefix". + :paramtype default_consistency_level: str or + ~azure.mgmt.cosmosdb.models.DefaultConsistencyLevel + :keyword max_staleness_prefix: When used with the Bounded Staleness consistency level, this + value represents the number of stale requests tolerated. Accepted range for this value is 1 – + 2,147,483,647. Required when defaultConsistencyPolicy is set to 'BoundedStaleness'. + :paramtype max_staleness_prefix: int + :keyword max_interval_in_seconds: When used with the Bounded Staleness consistency level, this + value represents the time amount of staleness (in seconds) tolerated. Accepted range for this + value is 5 - 86400. Required when defaultConsistencyPolicy is set to 'BoundedStaleness'. + :paramtype max_interval_in_seconds: int + """ + super().__init__(**kwargs) + self.default_consistency_level = default_consistency_level + self.max_staleness_prefix = max_staleness_prefix + self.max_interval_in_seconds = max_interval_in_seconds + + +class ContainerPartitionKey(_serialization.Model): + """The configuration of the partition key to be used for partitioning data into multiple + partitions. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar paths: List of paths using which data within the container can be partitioned. + :vartype paths: list[str] + :ivar kind: Indicates the kind of algorithm used for partitioning. For MultiHash, multiple + partition keys (upto three maximum) are supported for container create. Known values are: + "Hash", "Range", and "MultiHash". + :vartype kind: str or ~azure.mgmt.cosmosdb.models.PartitionKind + :ivar version: Indicates the version of the partition key definition. + :vartype version: int + :ivar system_key: Indicates if the container is using a system generated partition key. + :vartype system_key: bool + """ + + _validation = { + "version": {"maximum": 2, "minimum": 1}, + "system_key": {"readonly": True}, + } + + _attribute_map = { + "paths": {"key": "paths", "type": "[str]"}, + "kind": {"key": "kind", "type": "str"}, + "version": {"key": "version", "type": "int"}, + "system_key": {"key": "systemKey", "type": "bool"}, + } + + def __init__( + self, + *, + paths: Optional[List[str]] = None, + kind: Union[str, "_models.PartitionKind"] = "Hash", + version: Optional[int] = None, + **kwargs: Any + ) -> None: + """ + :keyword paths: List of paths using which data within the container can be partitioned. + :paramtype paths: list[str] + :keyword kind: Indicates the kind of algorithm used for partitioning. For MultiHash, multiple + partition keys (upto three maximum) are supported for container create. Known values are: + "Hash", "Range", and "MultiHash". + :paramtype kind: str or ~azure.mgmt.cosmosdb.models.PartitionKind + :keyword version: Indicates the version of the partition key definition. + :paramtype version: int + """ + super().__init__(**kwargs) + self.paths = paths + self.kind = kind + self.version = version + self.system_key = None + + +class ContinuousBackupInformation(_serialization.Model): + """Information about the status of continuous backups. + + :ivar latest_restorable_timestamp: The latest restorable timestamp for a resource. + :vartype latest_restorable_timestamp: str + """ + + _attribute_map = { + "latest_restorable_timestamp": {"key": "latestRestorableTimestamp", "type": "str"}, + } + + def __init__(self, *, latest_restorable_timestamp: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword latest_restorable_timestamp: The latest restorable timestamp for a resource. + :paramtype latest_restorable_timestamp: str + """ + super().__init__(**kwargs) + self.latest_restorable_timestamp = latest_restorable_timestamp + + +class ContinuousBackupRestoreLocation(_serialization.Model): + """Properties of the regional restorable account. + + :ivar location: The name of the continuous backup restore location. + :vartype location: str + """ + + _attribute_map = { + "location": {"key": "location", "type": "str"}, + } + + def __init__(self, *, location: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword location: The name of the continuous backup restore location. + :paramtype location: str + """ + super().__init__(**kwargs) + self.location = location + + +class ContinuousModeBackupPolicy(BackupPolicy): + """The object representing continuous mode backup policy. + + All required parameters must be populated in order to send to server. + + :ivar type: Describes the mode of backups. Required. Known values are: "Periodic" and + "Continuous". + :vartype type: str or ~azure.mgmt.cosmosdb.models.BackupPolicyType + :ivar migration_state: The object representing the state of the migration between the backup + policies. + :vartype migration_state: ~azure.mgmt.cosmosdb.models.BackupPolicyMigrationState + :ivar continuous_mode_properties: Configuration values for continuous mode backup. + :vartype continuous_mode_properties: ~azure.mgmt.cosmosdb.models.ContinuousModeProperties + """ + + _validation = { + "type": {"required": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "migration_state": {"key": "migrationState", "type": "BackupPolicyMigrationState"}, + "continuous_mode_properties": {"key": "continuousModeProperties", "type": "ContinuousModeProperties"}, + } + + def __init__( + self, + *, + migration_state: Optional["_models.BackupPolicyMigrationState"] = None, + continuous_mode_properties: Optional["_models.ContinuousModeProperties"] = None, + **kwargs: Any + ) -> None: + """ + :keyword migration_state: The object representing the state of the migration between the backup + policies. + :paramtype migration_state: ~azure.mgmt.cosmosdb.models.BackupPolicyMigrationState + :keyword continuous_mode_properties: Configuration values for continuous mode backup. + :paramtype continuous_mode_properties: ~azure.mgmt.cosmosdb.models.ContinuousModeProperties + """ + super().__init__(migration_state=migration_state, **kwargs) + self.type: str = "Continuous" + self.continuous_mode_properties = continuous_mode_properties + + +class ContinuousModeProperties(_serialization.Model): + """Configuration values for periodic mode backup. + + :ivar tier: Enum to indicate type of Continuos backup mode. Known values are: "Continuous7Days" + and "Continuous30Days". + :vartype tier: str or ~azure.mgmt.cosmosdb.models.ContinuousTier + """ + + _attribute_map = { + "tier": {"key": "tier", "type": "str"}, + } + + def __init__(self, *, tier: Optional[Union[str, "_models.ContinuousTier"]] = None, **kwargs: Any) -> None: + """ + :keyword tier: Enum to indicate type of Continuos backup mode. Known values are: + "Continuous7Days" and "Continuous30Days". + :paramtype tier: str or ~azure.mgmt.cosmosdb.models.ContinuousTier + """ + super().__init__(**kwargs) + self.tier = tier + + +class CorsPolicy(_serialization.Model): + """The CORS policy for the Cosmos DB database account. + + All required parameters must be populated in order to send to server. + + :ivar allowed_origins: The origin domains that are permitted to make a request against the + service via CORS. Required. + :vartype allowed_origins: str + :ivar allowed_methods: The methods (HTTP request verbs) that the origin domain may use for a + CORS request. + :vartype allowed_methods: str + :ivar allowed_headers: The request headers that the origin domain may specify on the CORS + request. + :vartype allowed_headers: str + :ivar exposed_headers: The response headers that may be sent in the response to the CORS + request and exposed by the browser to the request issuer. + :vartype exposed_headers: str + :ivar max_age_in_seconds: The maximum amount time that a browser should cache the preflight + OPTIONS request. + :vartype max_age_in_seconds: int + """ + + _validation = { + "allowed_origins": {"required": True}, + "max_age_in_seconds": {"maximum": 2147483647, "minimum": 1}, + } + + _attribute_map = { + "allowed_origins": {"key": "allowedOrigins", "type": "str"}, + "allowed_methods": {"key": "allowedMethods", "type": "str"}, + "allowed_headers": {"key": "allowedHeaders", "type": "str"}, + "exposed_headers": {"key": "exposedHeaders", "type": "str"}, + "max_age_in_seconds": {"key": "maxAgeInSeconds", "type": "int"}, + } + + def __init__( + self, + *, + allowed_origins: str, + allowed_methods: Optional[str] = None, + allowed_headers: Optional[str] = None, + exposed_headers: Optional[str] = None, + max_age_in_seconds: Optional[int] = None, + **kwargs: Any + ) -> None: + """ + :keyword allowed_origins: The origin domains that are permitted to make a request against the + service via CORS. Required. + :paramtype allowed_origins: str + :keyword allowed_methods: The methods (HTTP request verbs) that the origin domain may use for a + CORS request. + :paramtype allowed_methods: str + :keyword allowed_headers: The request headers that the origin domain may specify on the CORS + request. + :paramtype allowed_headers: str + :keyword exposed_headers: The response headers that may be sent in the response to the CORS + request and exposed by the browser to the request issuer. + :paramtype exposed_headers: str + :keyword max_age_in_seconds: The maximum amount time that a browser should cache the preflight + OPTIONS request. + :paramtype max_age_in_seconds: int + """ + super().__init__(**kwargs) + self.allowed_origins = allowed_origins + self.allowed_methods = allowed_methods + self.allowed_headers = allowed_headers + self.exposed_headers = exposed_headers + self.max_age_in_seconds = max_age_in_seconds + + +class CosmosCassandraDataTransferDataSourceSink(BaseCosmosDataTransferDataSourceSink): # pylint: disable=name-too-long + """A CosmosDB Cassandra API data source/sink. + + All required parameters must be populated in order to send to server. + + :ivar component: Known values are: "CosmosDBCassandra", "CosmosDBMongo", "CosmosDBMongoVCore", + "CosmosDBSql", and "AzureBlobStorage". + :vartype component: str or ~azure.mgmt.cosmosdb.models.DataTransferComponent + :ivar remote_account_name: + :vartype remote_account_name: str + :ivar keyspace_name: Required. + :vartype keyspace_name: str + :ivar table_name: Required. + :vartype table_name: str + """ + + _validation = { + "component": {"required": True}, + "keyspace_name": {"required": True}, + "table_name": {"required": True}, + } + + _attribute_map = { + "component": {"key": "component", "type": "str"}, + "remote_account_name": {"key": "remoteAccountName", "type": "str"}, + "keyspace_name": {"key": "keyspaceName", "type": "str"}, + "table_name": {"key": "tableName", "type": "str"}, + } + + def __init__( + self, *, keyspace_name: str, table_name: str, remote_account_name: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword remote_account_name: + :paramtype remote_account_name: str + :keyword keyspace_name: Required. + :paramtype keyspace_name: str + :keyword table_name: Required. + :paramtype table_name: str + """ + super().__init__(remote_account_name=remote_account_name, **kwargs) + self.component: str = "CosmosDBCassandra" + self.keyspace_name = keyspace_name + self.table_name = table_name + + +class CosmosMongoDataTransferDataSourceSink(BaseCosmosDataTransferDataSourceSink): + """A CosmosDB Mongo API data source/sink. + + All required parameters must be populated in order to send to server. + + :ivar component: Known values are: "CosmosDBCassandra", "CosmosDBMongo", "CosmosDBMongoVCore", + "CosmosDBSql", and "AzureBlobStorage". + :vartype component: str or ~azure.mgmt.cosmosdb.models.DataTransferComponent + :ivar remote_account_name: + :vartype remote_account_name: str + :ivar database_name: Required. + :vartype database_name: str + :ivar collection_name: Required. + :vartype collection_name: str + """ + + _validation = { + "component": {"required": True}, + "database_name": {"required": True}, + "collection_name": {"required": True}, + } + + _attribute_map = { + "component": {"key": "component", "type": "str"}, + "remote_account_name": {"key": "remoteAccountName", "type": "str"}, + "database_name": {"key": "databaseName", "type": "str"}, + "collection_name": {"key": "collectionName", "type": "str"}, + } + + def __init__( + self, *, database_name: str, collection_name: str, remote_account_name: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword remote_account_name: + :paramtype remote_account_name: str + :keyword database_name: Required. + :paramtype database_name: str + :keyword collection_name: Required. + :paramtype collection_name: str + """ + super().__init__(remote_account_name=remote_account_name, **kwargs) + self.component: str = "CosmosDBMongo" + self.database_name = database_name + self.collection_name = collection_name + + +class CosmosMongoVCoreDataTransferDataSourceSink(DataTransferDataSourceSink): # pylint: disable=name-too-long + """A CosmosDB Mongo vCore API data source/sink. + + All required parameters must be populated in order to send to server. + + :ivar component: Known values are: "CosmosDBCassandra", "CosmosDBMongo", "CosmosDBMongoVCore", + "CosmosDBSql", and "AzureBlobStorage". + :vartype component: str or ~azure.mgmt.cosmosdb.models.DataTransferComponent + :ivar database_name: Required. + :vartype database_name: str + :ivar collection_name: Required. + :vartype collection_name: str + :ivar host_name: + :vartype host_name: str + :ivar connection_string_key_vault_uri: + :vartype connection_string_key_vault_uri: str + """ + + _validation = { + "component": {"required": True}, + "database_name": {"required": True}, + "collection_name": {"required": True}, + } + + _attribute_map = { + "component": {"key": "component", "type": "str"}, + "database_name": {"key": "databaseName", "type": "str"}, + "collection_name": {"key": "collectionName", "type": "str"}, + "host_name": {"key": "hostName", "type": "str"}, + "connection_string_key_vault_uri": {"key": "connectionStringKeyVaultUri", "type": "str"}, + } + + def __init__( + self, + *, + database_name: str, + collection_name: str, + host_name: Optional[str] = None, + connection_string_key_vault_uri: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword database_name: Required. + :paramtype database_name: str + :keyword collection_name: Required. + :paramtype collection_name: str + :keyword host_name: + :paramtype host_name: str + :keyword connection_string_key_vault_uri: + :paramtype connection_string_key_vault_uri: str + """ + super().__init__(**kwargs) + self.component: str = "CosmosDBMongoVCore" + self.database_name = database_name + self.collection_name = collection_name + self.host_name = host_name + self.connection_string_key_vault_uri = connection_string_key_vault_uri + + +class CosmosSqlDataTransferDataSourceSink(BaseCosmosDataTransferDataSourceSink): + """A CosmosDB No Sql API data source/sink. + + All required parameters must be populated in order to send to server. + + :ivar component: Known values are: "CosmosDBCassandra", "CosmosDBMongo", "CosmosDBMongoVCore", + "CosmosDBSql", and "AzureBlobStorage". + :vartype component: str or ~azure.mgmt.cosmosdb.models.DataTransferComponent + :ivar remote_account_name: + :vartype remote_account_name: str + :ivar database_name: Required. + :vartype database_name: str + :ivar container_name: Required. + :vartype container_name: str + """ + + _validation = { + "component": {"required": True}, + "database_name": {"required": True}, + "container_name": {"required": True}, + } + + _attribute_map = { + "component": {"key": "component", "type": "str"}, + "remote_account_name": {"key": "remoteAccountName", "type": "str"}, + "database_name": {"key": "databaseName", "type": "str"}, + "container_name": {"key": "containerName", "type": "str"}, + } + + def __init__( + self, *, database_name: str, container_name: str, remote_account_name: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword remote_account_name: + :paramtype remote_account_name: str + :keyword database_name: Required. + :paramtype database_name: str + :keyword container_name: Required. + :paramtype container_name: str + """ + super().__init__(remote_account_name=remote_account_name, **kwargs) + self.component: str = "CosmosDBSql" + self.database_name = database_name + self.container_name = container_name + + +class CreateJobRequest(ARMProxyResource): + """Parameters to create Data Transfer Job. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: The unique resource identifier of the database account. + :vartype id: str + :ivar name: The name of the database account. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar properties: Data Transfer Create Job Properties. Required. + :vartype properties: ~azure.mgmt.cosmosdb.models.DataTransferJobProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "properties": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "properties": {"key": "properties", "type": "DataTransferJobProperties"}, + } + + def __init__(self, *, properties: "_models.DataTransferJobProperties", **kwargs: Any) -> None: + """ + :keyword properties: Data Transfer Create Job Properties. Required. + :paramtype properties: ~azure.mgmt.cosmosdb.models.DataTransferJobProperties + """ + super().__init__(**kwargs) + self.properties = properties + + +class CreateUpdateOptions(_serialization.Model): + """CreateUpdateOptions are a list of key-value pairs that describe the resource. Supported keys + are "If-Match", "If-None-Match", "Session-Token" and "Throughput". + + :ivar throughput: Request Units per second. For example, "throughput": 10000. + :vartype throughput: int + :ivar autoscale_settings: Specifies the Autoscale settings. Note: Either throughput or + autoscaleSettings is required, but not both. + :vartype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettings + """ + + _attribute_map = { + "throughput": {"key": "throughput", "type": "int"}, + "autoscale_settings": {"key": "autoscaleSettings", "type": "AutoscaleSettings"}, + } + + def __init__( + self, + *, + throughput: Optional[int] = None, + autoscale_settings: Optional["_models.AutoscaleSettings"] = None, + **kwargs: Any + ) -> None: + """ + :keyword throughput: Request Units per second. For example, "throughput": 10000. + :paramtype throughput: int + :keyword autoscale_settings: Specifies the Autoscale settings. Note: Either throughput or + autoscaleSettings is required, but not both. + :paramtype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettings + """ + super().__init__(**kwargs) + self.throughput = throughput + self.autoscale_settings = autoscale_settings + + +class DatabaseAccountConnectionString(_serialization.Model): + """Connection string for the Cosmos DB account. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar connection_string: Value of the connection string. + :vartype connection_string: str + :ivar description: Description of the connection string. + :vartype description: str + :ivar key_kind: Kind of the connection string key. Known values are: "Primary", "Secondary", + "PrimaryReadonly", and "SecondaryReadonly". + :vartype key_kind: str or ~azure.mgmt.cosmosdb.models.Kind + :ivar type: Type of the connection string. Known values are: "Sql", "Table", "MongoDB", + "Cassandra", "CassandraConnectorMetadata", "Gremlin", "SqlDedicatedGateway", "GremlinV2", and + "Undefined". + :vartype type: str or ~azure.mgmt.cosmosdb.models.Type + """ + + _validation = { + "connection_string": {"readonly": True}, + "description": {"readonly": True}, + "key_kind": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "connection_string": {"key": "connectionString", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "key_kind": {"key": "keyKind", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.connection_string = None + self.description = None + self.key_kind = None + self.type = None + + +class DatabaseAccountCreateUpdateParameters(ARMResourceProperties): # pylint: disable=too-many-instance-attributes + """Parameters to create and update Cosmos DB database accounts. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar kind: Indicates the type of database account. This can only be set at database account + creation. Known values are: "GlobalDocumentDB", "MongoDB", and "Parse". + :vartype kind: str or ~azure.mgmt.cosmosdb.models.DatabaseAccountKind + :ivar consistency_policy: The consistency policy for the Cosmos DB account. + :vartype consistency_policy: ~azure.mgmt.cosmosdb.models.ConsistencyPolicy + :ivar locations: An array that contains the georeplication locations enabled for the Cosmos DB + account. Required. + :vartype locations: list[~azure.mgmt.cosmosdb.models.Location] + :ivar database_account_offer_type: The offer type for the database. Required. Default value is + "Standard". + :vartype database_account_offer_type: str + :ivar ip_rules: List of IpRules. + :vartype ip_rules: list[~azure.mgmt.cosmosdb.models.IpAddressOrRange] + :ivar is_virtual_network_filter_enabled: Flag to indicate whether to enable/disable Virtual + Network ACL rules. + :vartype is_virtual_network_filter_enabled: bool + :ivar enable_automatic_failover: Enables automatic failover of the write region in the rare + event that the region is unavailable due to an outage. Automatic failover will result in a new + write region for the account and is chosen based on the failover priorities configured for the + account. + :vartype enable_automatic_failover: bool + :ivar capabilities: List of Cosmos DB capabilities for the account. + :vartype capabilities: list[~azure.mgmt.cosmosdb.models.Capability] + :ivar virtual_network_rules: List of Virtual Network ACL rules configured for the Cosmos DB + account. + :vartype virtual_network_rules: list[~azure.mgmt.cosmosdb.models.VirtualNetworkRule] + :ivar enable_multiple_write_locations: Enables the account to write in multiple locations. + :vartype enable_multiple_write_locations: bool + :ivar enable_cassandra_connector: Enables the cassandra connector on the Cosmos DB C* account. + :vartype enable_cassandra_connector: bool + :ivar connector_offer: The cassandra connector offer type for the Cosmos DB database C* + account. "Small" + :vartype connector_offer: str or ~azure.mgmt.cosmosdb.models.ConnectorOffer + :ivar disable_key_based_metadata_write_access: Disable write operations on metadata resources + (databases, containers, throughput) via account keys. + :vartype disable_key_based_metadata_write_access: bool + :ivar key_vault_key_uri: The URI of the key vault. + :vartype key_vault_key_uri: str + :ivar default_identity: The default identity for accessing key vault used in features like + customer managed keys. The default identity needs to be explicitly set by the users. It can be + "FirstPartyIdentity", "SystemAssignedIdentity" and more. + :vartype default_identity: str + :ivar public_network_access: Whether requests from Public Network are allowed. Known values + are: "Enabled", "Disabled", and "SecuredByPerimeter". + :vartype public_network_access: str or ~azure.mgmt.cosmosdb.models.PublicNetworkAccess + :ivar enable_free_tier: Flag to indicate whether Free Tier is enabled. + :vartype enable_free_tier: bool + :ivar api_properties: API specific properties. Currently, supported only for MongoDB API. + :vartype api_properties: ~azure.mgmt.cosmosdb.models.ApiProperties + :ivar enable_analytical_storage: Flag to indicate whether to enable storage analytics. + :vartype enable_analytical_storage: bool + :ivar analytical_storage_configuration: Analytical storage specific properties. + :vartype analytical_storage_configuration: + ~azure.mgmt.cosmosdb.models.AnalyticalStorageConfiguration + :ivar create_mode: Enum to indicate the mode of account creation. Known values are: "Default" + and "Restore". + :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + :ivar backup_policy: The object representing the policy for taking backups on an account. + :vartype backup_policy: ~azure.mgmt.cosmosdb.models.BackupPolicy + :ivar cors: The CORS policy for the Cosmos DB database account. + :vartype cors: list[~azure.mgmt.cosmosdb.models.CorsPolicy] + :ivar network_acl_bypass: Indicates what services are allowed to bypass firewall checks. Known + values are: "None" and "AzureServices". + :vartype network_acl_bypass: str or ~azure.mgmt.cosmosdb.models.NetworkAclBypass + :ivar network_acl_bypass_resource_ids: An array that contains the Resource Ids for Network Acl + Bypass for the Cosmos DB account. + :vartype network_acl_bypass_resource_ids: list[str] + :ivar diagnostic_log_settings: The Object representing the different Diagnostic log settings + for the Cosmos DB Account. + :vartype diagnostic_log_settings: ~azure.mgmt.cosmosdb.models.DiagnosticLogSettings + :ivar disable_local_auth: Opt-out of local authentication and ensure only MSI and AAD can be + used exclusively for authentication. + :vartype disable_local_auth: bool + :ivar restore_parameters: Parameters to indicate the information about the restore. + :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.RestoreParameters + :ivar capacity: The object that represents all properties related to capacity enforcement on an + account. + :vartype capacity: ~azure.mgmt.cosmosdb.models.Capacity + :ivar capacity_mode: Indicates the capacityMode of the Cosmos DB account. Known values are: + "None", "Provisioned", and "Serverless". + :vartype capacity_mode: str or ~azure.mgmt.cosmosdb.models.CapacityMode + :ivar enable_materialized_views: Flag to indicate whether to enable MaterializedViews on the + Cosmos DB account. + :vartype enable_materialized_views: bool + :ivar keys_metadata: This property is ignored during the update/create operation, as the + metadata is read-only. The object represents the metadata for the Account Keys of the Cosmos DB + account. + :vartype keys_metadata: ~azure.mgmt.cosmosdb.models.DatabaseAccountKeysMetadata + :ivar enable_partition_merge: Flag to indicate enabling/disabling of Partition Merge feature on + the account. + :vartype enable_partition_merge: bool + :ivar enable_burst_capacity: Flag to indicate enabling/disabling of Burst Capacity Preview + feature on the account. + :vartype enable_burst_capacity: bool + :ivar minimal_tls_version: Indicates the minimum allowed Tls version. The default is Tls 1.0, + except for Cassandra and Mongo API's, which only work with Tls 1.2. Known values are: "Tls", + "Tls11", and "Tls12". + :vartype minimal_tls_version: str or ~azure.mgmt.cosmosdb.models.MinimalTlsVersion + :ivar customer_managed_key_status: Indicates the status of the Customer Managed Key feature on + the account. In case there are errors, the property provides troubleshooting guidance. + :vartype customer_managed_key_status: str + :ivar enable_priority_based_execution: Flag to indicate enabling/disabling of Priority Based + Execution Preview feature on the account. + :vartype enable_priority_based_execution: bool + :ivar default_priority_level: Enum to indicate default Priority Level of request for Priority + Based Execution. Known values are: "High" and "Low". + :vartype default_priority_level: str or ~azure.mgmt.cosmosdb.models.DefaultPriorityLevel + :ivar enable_per_region_per_partition_autoscale: Flag to indicate enabling/disabling of + Per-Region Per-partition autoscale Preview feature on the account. + :vartype enable_per_region_per_partition_autoscale: bool + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "locations": {"required": True}, + "database_account_offer_type": {"required": True, "constant": True}, + "keys_metadata": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "kind": {"key": "kind", "type": "str"}, + "consistency_policy": {"key": "properties.consistencyPolicy", "type": "ConsistencyPolicy"}, + "locations": {"key": "properties.locations", "type": "[Location]"}, + "database_account_offer_type": {"key": "properties.databaseAccountOfferType", "type": "str"}, + "ip_rules": {"key": "properties.ipRules", "type": "[IpAddressOrRange]"}, + "is_virtual_network_filter_enabled": {"key": "properties.isVirtualNetworkFilterEnabled", "type": "bool"}, + "enable_automatic_failover": {"key": "properties.enableAutomaticFailover", "type": "bool"}, + "capabilities": {"key": "properties.capabilities", "type": "[Capability]"}, + "virtual_network_rules": {"key": "properties.virtualNetworkRules", "type": "[VirtualNetworkRule]"}, + "enable_multiple_write_locations": {"key": "properties.enableMultipleWriteLocations", "type": "bool"}, + "enable_cassandra_connector": {"key": "properties.enableCassandraConnector", "type": "bool"}, + "connector_offer": {"key": "properties.connectorOffer", "type": "str"}, + "disable_key_based_metadata_write_access": { + "key": "properties.disableKeyBasedMetadataWriteAccess", + "type": "bool", + }, + "key_vault_key_uri": {"key": "properties.keyVaultKeyUri", "type": "str"}, + "default_identity": {"key": "properties.defaultIdentity", "type": "str"}, + "public_network_access": {"key": "properties.publicNetworkAccess", "type": "str"}, + "enable_free_tier": {"key": "properties.enableFreeTier", "type": "bool"}, + "api_properties": {"key": "properties.apiProperties", "type": "ApiProperties"}, + "enable_analytical_storage": {"key": "properties.enableAnalyticalStorage", "type": "bool"}, + "analytical_storage_configuration": { + "key": "properties.analyticalStorageConfiguration", + "type": "AnalyticalStorageConfiguration", + }, + "create_mode": {"key": "properties.createMode", "type": "str"}, + "backup_policy": {"key": "properties.backupPolicy", "type": "BackupPolicy"}, + "cors": {"key": "properties.cors", "type": "[CorsPolicy]"}, + "network_acl_bypass": {"key": "properties.networkAclBypass", "type": "str"}, + "network_acl_bypass_resource_ids": {"key": "properties.networkAclBypassResourceIds", "type": "[str]"}, + "diagnostic_log_settings": {"key": "properties.diagnosticLogSettings", "type": "DiagnosticLogSettings"}, + "disable_local_auth": {"key": "properties.disableLocalAuth", "type": "bool"}, + "restore_parameters": {"key": "properties.restoreParameters", "type": "RestoreParameters"}, + "capacity": {"key": "properties.capacity", "type": "Capacity"}, + "capacity_mode": {"key": "properties.capacityMode", "type": "str"}, + "enable_materialized_views": {"key": "properties.enableMaterializedViews", "type": "bool"}, + "keys_metadata": {"key": "properties.keysMetadata", "type": "DatabaseAccountKeysMetadata"}, + "enable_partition_merge": {"key": "properties.enablePartitionMerge", "type": "bool"}, + "enable_burst_capacity": {"key": "properties.enableBurstCapacity", "type": "bool"}, + "minimal_tls_version": {"key": "properties.minimalTlsVersion", "type": "str"}, + "customer_managed_key_status": {"key": "properties.customerManagedKeyStatus", "type": "str"}, + "enable_priority_based_execution": {"key": "properties.enablePriorityBasedExecution", "type": "bool"}, + "default_priority_level": {"key": "properties.defaultPriorityLevel", "type": "str"}, + "enable_per_region_per_partition_autoscale": { + "key": "properties.enablePerRegionPerPartitionAutoscale", + "type": "bool", + }, + } + + database_account_offer_type = "Standard" + + def __init__( # pylint: disable=too-many-locals + self, + *, + locations: List["_models.Location"], + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + kind: Optional[Union[str, "_models.DatabaseAccountKind"]] = None, + consistency_policy: Optional["_models.ConsistencyPolicy"] = None, + ip_rules: Optional[List["_models.IpAddressOrRange"]] = None, + is_virtual_network_filter_enabled: Optional[bool] = None, + enable_automatic_failover: Optional[bool] = None, + capabilities: Optional[List["_models.Capability"]] = None, + virtual_network_rules: Optional[List["_models.VirtualNetworkRule"]] = None, + enable_multiple_write_locations: Optional[bool] = None, + enable_cassandra_connector: Optional[bool] = None, + connector_offer: Optional[Union[str, "_models.ConnectorOffer"]] = None, + disable_key_based_metadata_write_access: Optional[bool] = None, + key_vault_key_uri: Optional[str] = None, + default_identity: Optional[str] = None, + public_network_access: Optional[Union[str, "_models.PublicNetworkAccess"]] = None, + enable_free_tier: Optional[bool] = None, + api_properties: Optional["_models.ApiProperties"] = None, + enable_analytical_storage: Optional[bool] = None, + analytical_storage_configuration: Optional["_models.AnalyticalStorageConfiguration"] = None, + create_mode: Union[str, "_models.CreateMode"] = "Default", + backup_policy: Optional["_models.BackupPolicy"] = None, + cors: Optional[List["_models.CorsPolicy"]] = None, + network_acl_bypass: Optional[Union[str, "_models.NetworkAclBypass"]] = None, + network_acl_bypass_resource_ids: Optional[List[str]] = None, + diagnostic_log_settings: Optional["_models.DiagnosticLogSettings"] = None, + disable_local_auth: Optional[bool] = None, + restore_parameters: Optional["_models.RestoreParameters"] = None, + capacity: Optional["_models.Capacity"] = None, + capacity_mode: Optional[Union[str, "_models.CapacityMode"]] = None, + enable_materialized_views: Optional[bool] = None, + enable_partition_merge: Optional[bool] = None, + enable_burst_capacity: Optional[bool] = None, + minimal_tls_version: Optional[Union[str, "_models.MinimalTlsVersion"]] = None, + customer_managed_key_status: Optional[str] = None, + enable_priority_based_execution: Optional[bool] = None, + default_priority_level: Optional[Union[str, "_models.DefaultPriorityLevel"]] = None, + enable_per_region_per_partition_autoscale: Optional[bool] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword kind: Indicates the type of database account. This can only be set at database account + creation. Known values are: "GlobalDocumentDB", "MongoDB", and "Parse". + :paramtype kind: str or ~azure.mgmt.cosmosdb.models.DatabaseAccountKind + :keyword consistency_policy: The consistency policy for the Cosmos DB account. + :paramtype consistency_policy: ~azure.mgmt.cosmosdb.models.ConsistencyPolicy + :keyword locations: An array that contains the georeplication locations enabled for the Cosmos + DB account. Required. + :paramtype locations: list[~azure.mgmt.cosmosdb.models.Location] + :keyword ip_rules: List of IpRules. + :paramtype ip_rules: list[~azure.mgmt.cosmosdb.models.IpAddressOrRange] + :keyword is_virtual_network_filter_enabled: Flag to indicate whether to enable/disable Virtual + Network ACL rules. + :paramtype is_virtual_network_filter_enabled: bool + :keyword enable_automatic_failover: Enables automatic failover of the write region in the rare + event that the region is unavailable due to an outage. Automatic failover will result in a new + write region for the account and is chosen based on the failover priorities configured for the + account. + :paramtype enable_automatic_failover: bool + :keyword capabilities: List of Cosmos DB capabilities for the account. + :paramtype capabilities: list[~azure.mgmt.cosmosdb.models.Capability] + :keyword virtual_network_rules: List of Virtual Network ACL rules configured for the Cosmos DB + account. + :paramtype virtual_network_rules: list[~azure.mgmt.cosmosdb.models.VirtualNetworkRule] + :keyword enable_multiple_write_locations: Enables the account to write in multiple locations. + :paramtype enable_multiple_write_locations: bool + :keyword enable_cassandra_connector: Enables the cassandra connector on the Cosmos DB C* + account. + :paramtype enable_cassandra_connector: bool + :keyword connector_offer: The cassandra connector offer type for the Cosmos DB database C* + account. "Small" + :paramtype connector_offer: str or ~azure.mgmt.cosmosdb.models.ConnectorOffer + :keyword disable_key_based_metadata_write_access: Disable write operations on metadata + resources (databases, containers, throughput) via account keys. + :paramtype disable_key_based_metadata_write_access: bool + :keyword key_vault_key_uri: The URI of the key vault. + :paramtype key_vault_key_uri: str + :keyword default_identity: The default identity for accessing key vault used in features like + customer managed keys. The default identity needs to be explicitly set by the users. It can be + "FirstPartyIdentity", "SystemAssignedIdentity" and more. + :paramtype default_identity: str + :keyword public_network_access: Whether requests from Public Network are allowed. Known values + are: "Enabled", "Disabled", and "SecuredByPerimeter". + :paramtype public_network_access: str or ~azure.mgmt.cosmosdb.models.PublicNetworkAccess + :keyword enable_free_tier: Flag to indicate whether Free Tier is enabled. + :paramtype enable_free_tier: bool + :keyword api_properties: API specific properties. Currently, supported only for MongoDB API. + :paramtype api_properties: ~azure.mgmt.cosmosdb.models.ApiProperties + :keyword enable_analytical_storage: Flag to indicate whether to enable storage analytics. + :paramtype enable_analytical_storage: bool + :keyword analytical_storage_configuration: Analytical storage specific properties. + :paramtype analytical_storage_configuration: + ~azure.mgmt.cosmosdb.models.AnalyticalStorageConfiguration + :keyword create_mode: Enum to indicate the mode of account creation. Known values are: + "Default" and "Restore". + :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + :keyword backup_policy: The object representing the policy for taking backups on an account. + :paramtype backup_policy: ~azure.mgmt.cosmosdb.models.BackupPolicy + :keyword cors: The CORS policy for the Cosmos DB database account. + :paramtype cors: list[~azure.mgmt.cosmosdb.models.CorsPolicy] + :keyword network_acl_bypass: Indicates what services are allowed to bypass firewall checks. + Known values are: "None" and "AzureServices". + :paramtype network_acl_bypass: str or ~azure.mgmt.cosmosdb.models.NetworkAclBypass + :keyword network_acl_bypass_resource_ids: An array that contains the Resource Ids for Network + Acl Bypass for the Cosmos DB account. + :paramtype network_acl_bypass_resource_ids: list[str] + :keyword diagnostic_log_settings: The Object representing the different Diagnostic log settings + for the Cosmos DB Account. + :paramtype diagnostic_log_settings: ~azure.mgmt.cosmosdb.models.DiagnosticLogSettings + :keyword disable_local_auth: Opt-out of local authentication and ensure only MSI and AAD can be + used exclusively for authentication. + :paramtype disable_local_auth: bool + :keyword restore_parameters: Parameters to indicate the information about the restore. + :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.RestoreParameters + :keyword capacity: The object that represents all properties related to capacity enforcement on + an account. + :paramtype capacity: ~azure.mgmt.cosmosdb.models.Capacity + :keyword capacity_mode: Indicates the capacityMode of the Cosmos DB account. Known values are: + "None", "Provisioned", and "Serverless". + :paramtype capacity_mode: str or ~azure.mgmt.cosmosdb.models.CapacityMode + :keyword enable_materialized_views: Flag to indicate whether to enable MaterializedViews on the + Cosmos DB account. + :paramtype enable_materialized_views: bool + :keyword enable_partition_merge: Flag to indicate enabling/disabling of Partition Merge feature + on the account. + :paramtype enable_partition_merge: bool + :keyword enable_burst_capacity: Flag to indicate enabling/disabling of Burst Capacity Preview + feature on the account. + :paramtype enable_burst_capacity: bool + :keyword minimal_tls_version: Indicates the minimum allowed Tls version. The default is Tls + 1.0, except for Cassandra and Mongo API's, which only work with Tls 1.2. Known values are: + "Tls", "Tls11", and "Tls12". + :paramtype minimal_tls_version: str or ~azure.mgmt.cosmosdb.models.MinimalTlsVersion + :keyword customer_managed_key_status: Indicates the status of the Customer Managed Key feature + on the account. In case there are errors, the property provides troubleshooting guidance. + :paramtype customer_managed_key_status: str + :keyword enable_priority_based_execution: Flag to indicate enabling/disabling of Priority Based + Execution Preview feature on the account. + :paramtype enable_priority_based_execution: bool + :keyword default_priority_level: Enum to indicate default Priority Level of request for + Priority Based Execution. Known values are: "High" and "Low". + :paramtype default_priority_level: str or ~azure.mgmt.cosmosdb.models.DefaultPriorityLevel + :keyword enable_per_region_per_partition_autoscale: Flag to indicate enabling/disabling of + Per-Region Per-partition autoscale Preview feature on the account. + :paramtype enable_per_region_per_partition_autoscale: bool + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.kind = kind + self.consistency_policy = consistency_policy + self.locations = locations + self.ip_rules = ip_rules + self.is_virtual_network_filter_enabled = is_virtual_network_filter_enabled + self.enable_automatic_failover = enable_automatic_failover + self.capabilities = capabilities + self.virtual_network_rules = virtual_network_rules + self.enable_multiple_write_locations = enable_multiple_write_locations + self.enable_cassandra_connector = enable_cassandra_connector + self.connector_offer = connector_offer + self.disable_key_based_metadata_write_access = disable_key_based_metadata_write_access + self.key_vault_key_uri = key_vault_key_uri + self.default_identity = default_identity + self.public_network_access = public_network_access + self.enable_free_tier = enable_free_tier + self.api_properties = api_properties + self.enable_analytical_storage = enable_analytical_storage + self.analytical_storage_configuration = analytical_storage_configuration + self.create_mode = create_mode + self.backup_policy = backup_policy + self.cors = cors + self.network_acl_bypass = network_acl_bypass + self.network_acl_bypass_resource_ids = network_acl_bypass_resource_ids + self.diagnostic_log_settings = diagnostic_log_settings + self.disable_local_auth = disable_local_auth + self.restore_parameters = restore_parameters + self.capacity = capacity + self.capacity_mode = capacity_mode + self.enable_materialized_views = enable_materialized_views + self.keys_metadata = None + self.enable_partition_merge = enable_partition_merge + self.enable_burst_capacity = enable_burst_capacity + self.minimal_tls_version = minimal_tls_version + self.customer_managed_key_status = customer_managed_key_status + self.enable_priority_based_execution = enable_priority_based_execution + self.default_priority_level = default_priority_level + self.enable_per_region_per_partition_autoscale = enable_per_region_per_partition_autoscale + + +class DatabaseAccountGetResults(ARMResourceProperties): # pylint: disable=too-many-instance-attributes + """An Azure Cosmos DB database account. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar kind: Indicates the type of database account. This can only be set at database account + creation. Known values are: "GlobalDocumentDB", "MongoDB", and "Parse". + :vartype kind: str or ~azure.mgmt.cosmosdb.models.DatabaseAccountKind + :ivar system_data: The system meta data relating to this resource. + :vartype system_data: ~azure.mgmt.cosmosdb.models.SystemData + :ivar provisioning_state: The status of the Cosmos DB account at the time the operation was + called. The status can be one of following. 'Creating' – the Cosmos DB account is being + created. When an account is in Creating state, only properties that are specified as input for + the Create Cosmos DB account operation are returned. 'Succeeded' – the Cosmos DB account is + active for use. 'Updating' – the Cosmos DB account is being updated. 'Deleting' – the Cosmos DB + account is being deleted. 'Failed' – the Cosmos DB account failed creation. 'DeletionFailed' – + the Cosmos DB account deletion failed. + :vartype provisioning_state: str + :ivar document_endpoint: The connection endpoint for the Cosmos DB database account. + :vartype document_endpoint: str + :ivar database_account_offer_type: The offer type for the Cosmos DB database account. Default + value: Standard. Default value is "Standard". + :vartype database_account_offer_type: str + :ivar ip_rules: List of IpRules. + :vartype ip_rules: list[~azure.mgmt.cosmosdb.models.IpAddressOrRange] + :ivar is_virtual_network_filter_enabled: Flag to indicate whether to enable/disable Virtual + Network ACL rules. + :vartype is_virtual_network_filter_enabled: bool + :ivar enable_automatic_failover: Enables automatic failover of the write region in the rare + event that the region is unavailable due to an outage. Automatic failover will result in a new + write region for the account and is chosen based on the failover priorities configured for the + account. + :vartype enable_automatic_failover: bool + :ivar consistency_policy: The consistency policy for the Cosmos DB database account. + :vartype consistency_policy: ~azure.mgmt.cosmosdb.models.ConsistencyPolicy + :ivar capabilities: List of Cosmos DB capabilities for the account. + :vartype capabilities: list[~azure.mgmt.cosmosdb.models.Capability] + :ivar write_locations: An array that contains the write location for the Cosmos DB account. + :vartype write_locations: list[~azure.mgmt.cosmosdb.models.Location] + :ivar read_locations: An array that contains of the read locations enabled for the Cosmos DB + account. + :vartype read_locations: list[~azure.mgmt.cosmosdb.models.Location] + :ivar locations: An array that contains all of the locations enabled for the Cosmos DB account. + :vartype locations: list[~azure.mgmt.cosmosdb.models.Location] + :ivar failover_policies: An array that contains the regions ordered by their failover + priorities. + :vartype failover_policies: list[~azure.mgmt.cosmosdb.models.FailoverPolicy] + :ivar virtual_network_rules: List of Virtual Network ACL rules configured for the Cosmos DB + account. + :vartype virtual_network_rules: list[~azure.mgmt.cosmosdb.models.VirtualNetworkRule] + :ivar private_endpoint_connections: List of Private Endpoint Connections configured for the + Cosmos DB account. + :vartype private_endpoint_connections: + list[~azure.mgmt.cosmosdb.models.PrivateEndpointConnection] + :ivar enable_multiple_write_locations: Enables the account to write in multiple locations. + :vartype enable_multiple_write_locations: bool + :ivar enable_cassandra_connector: Enables the cassandra connector on the Cosmos DB C* account. + :vartype enable_cassandra_connector: bool + :ivar connector_offer: The cassandra connector offer type for the Cosmos DB database C* + account. "Small" + :vartype connector_offer: str or ~azure.mgmt.cosmosdb.models.ConnectorOffer + :ivar disable_key_based_metadata_write_access: Disable write operations on metadata resources + (databases, containers, throughput) via account keys. + :vartype disable_key_based_metadata_write_access: bool + :ivar key_vault_key_uri: The URI of the key vault. + :vartype key_vault_key_uri: str + :ivar default_identity: The default identity for accessing key vault used in features like + customer managed keys. The default identity needs to be explicitly set by the users. It can be + "FirstPartyIdentity", "SystemAssignedIdentity" and more. + :vartype default_identity: str + :ivar public_network_access: Whether requests from Public Network are allowed. Known values + are: "Enabled", "Disabled", and "SecuredByPerimeter". + :vartype public_network_access: str or ~azure.mgmt.cosmosdb.models.PublicNetworkAccess + :ivar enable_free_tier: Flag to indicate whether Free Tier is enabled. + :vartype enable_free_tier: bool + :ivar api_properties: API specific properties. + :vartype api_properties: ~azure.mgmt.cosmosdb.models.ApiProperties + :ivar enable_analytical_storage: Flag to indicate whether to enable storage analytics. + :vartype enable_analytical_storage: bool + :ivar analytical_storage_configuration: Analytical storage specific properties. + :vartype analytical_storage_configuration: + ~azure.mgmt.cosmosdb.models.AnalyticalStorageConfiguration + :ivar instance_id: A unique identifier assigned to the database account. + :vartype instance_id: str + :ivar create_mode: Enum to indicate the mode of account creation. Known values are: "Default" + and "Restore". + :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + :ivar restore_parameters: Parameters to indicate the information about the restore. + :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.RestoreParameters + :ivar backup_policy: The object representing the policy for taking backups on an account. + :vartype backup_policy: ~azure.mgmt.cosmosdb.models.BackupPolicy + :ivar cors: The CORS policy for the Cosmos DB database account. + :vartype cors: list[~azure.mgmt.cosmosdb.models.CorsPolicy] + :ivar network_acl_bypass: Indicates what services are allowed to bypass firewall checks. Known + values are: "None" and "AzureServices". + :vartype network_acl_bypass: str or ~azure.mgmt.cosmosdb.models.NetworkAclBypass + :ivar network_acl_bypass_resource_ids: An array that contains the Resource Ids for Network Acl + Bypass for the Cosmos DB account. + :vartype network_acl_bypass_resource_ids: list[str] + :ivar diagnostic_log_settings: The Object representing the different Diagnostic log settings + for the Cosmos DB Account. + :vartype diagnostic_log_settings: ~azure.mgmt.cosmosdb.models.DiagnosticLogSettings + :ivar disable_local_auth: Opt-out of local authentication and ensure only MSI and AAD can be + used exclusively for authentication. + :vartype disable_local_auth: bool + :ivar capacity: The object that represents all properties related to capacity enforcement on an + account. + :vartype capacity: ~azure.mgmt.cosmosdb.models.Capacity + :ivar capacity_mode: Indicates the capacityMode of the Cosmos DB account. Known values are: + "None", "Provisioned", and "Serverless". + :vartype capacity_mode: str or ~azure.mgmt.cosmosdb.models.CapacityMode + :ivar capacity_mode_change_transition_state: The object that represents the migration state for + the CapacityMode of the Cosmos DB account. + :vartype capacity_mode_change_transition_state: + ~azure.mgmt.cosmosdb.models.CapacityModeChangeTransitionState + :ivar enable_materialized_views: Flag to indicate whether to enable MaterializedViews on the + Cosmos DB account. + :vartype enable_materialized_views: bool + :ivar keys_metadata: The object that represents the metadata for the Account Keys of the Cosmos + DB account. + :vartype keys_metadata: ~azure.mgmt.cosmosdb.models.DatabaseAccountKeysMetadata + :ivar enable_partition_merge: Flag to indicate enabling/disabling of Partition Merge feature on + the account. + :vartype enable_partition_merge: bool + :ivar enable_burst_capacity: Flag to indicate enabling/disabling of Burst Capacity Preview + feature on the account. + :vartype enable_burst_capacity: bool + :ivar minimal_tls_version: Indicates the minimum allowed Tls version. The default is Tls 1.0, + except for Cassandra and Mongo API's, which only work with Tls 1.2. Known values are: "Tls", + "Tls11", and "Tls12". + :vartype minimal_tls_version: str or ~azure.mgmt.cosmosdb.models.MinimalTlsVersion + :ivar customer_managed_key_status: Indicates the status of the Customer Managed Key feature on + the account. In case there are errors, the property provides troubleshooting guidance. + :vartype customer_managed_key_status: str + :ivar enable_priority_based_execution: Flag to indicate enabling/disabling of Priority Based + Execution Preview feature on the account. + :vartype enable_priority_based_execution: bool + :ivar default_priority_level: Enum to indicate default Priority Level of request for Priority + Based Execution. Known values are: "High" and "Low". + :vartype default_priority_level: str or ~azure.mgmt.cosmosdb.models.DefaultPriorityLevel + :ivar enable_per_region_per_partition_autoscale: Flag to indicate enabling/disabling of + Per-Region Per-partition autoscale Preview feature on the account. + :vartype enable_per_region_per_partition_autoscale: bool + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + "provisioning_state": {"readonly": True}, + "document_endpoint": {"readonly": True}, + "database_account_offer_type": {"readonly": True}, + "write_locations": {"readonly": True}, + "read_locations": {"readonly": True}, + "locations": {"readonly": True}, + "failover_policies": {"readonly": True}, + "private_endpoint_connections": {"readonly": True}, + "instance_id": {"readonly": True}, + "keys_metadata": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "kind": {"key": "kind", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "document_endpoint": {"key": "properties.documentEndpoint", "type": "str"}, + "database_account_offer_type": {"key": "properties.databaseAccountOfferType", "type": "str"}, + "ip_rules": {"key": "properties.ipRules", "type": "[IpAddressOrRange]"}, + "is_virtual_network_filter_enabled": {"key": "properties.isVirtualNetworkFilterEnabled", "type": "bool"}, + "enable_automatic_failover": {"key": "properties.enableAutomaticFailover", "type": "bool"}, + "consistency_policy": {"key": "properties.consistencyPolicy", "type": "ConsistencyPolicy"}, + "capabilities": {"key": "properties.capabilities", "type": "[Capability]"}, + "write_locations": {"key": "properties.writeLocations", "type": "[Location]"}, + "read_locations": {"key": "properties.readLocations", "type": "[Location]"}, + "locations": {"key": "properties.locations", "type": "[Location]"}, + "failover_policies": {"key": "properties.failoverPolicies", "type": "[FailoverPolicy]"}, + "virtual_network_rules": {"key": "properties.virtualNetworkRules", "type": "[VirtualNetworkRule]"}, + "private_endpoint_connections": { + "key": "properties.privateEndpointConnections", + "type": "[PrivateEndpointConnection]", + }, + "enable_multiple_write_locations": {"key": "properties.enableMultipleWriteLocations", "type": "bool"}, + "enable_cassandra_connector": {"key": "properties.enableCassandraConnector", "type": "bool"}, + "connector_offer": {"key": "properties.connectorOffer", "type": "str"}, + "disable_key_based_metadata_write_access": { + "key": "properties.disableKeyBasedMetadataWriteAccess", + "type": "bool", + }, + "key_vault_key_uri": {"key": "properties.keyVaultKeyUri", "type": "str"}, + "default_identity": {"key": "properties.defaultIdentity", "type": "str"}, + "public_network_access": {"key": "properties.publicNetworkAccess", "type": "str"}, + "enable_free_tier": {"key": "properties.enableFreeTier", "type": "bool"}, + "api_properties": {"key": "properties.apiProperties", "type": "ApiProperties"}, + "enable_analytical_storage": {"key": "properties.enableAnalyticalStorage", "type": "bool"}, + "analytical_storage_configuration": { + "key": "properties.analyticalStorageConfiguration", + "type": "AnalyticalStorageConfiguration", + }, + "instance_id": {"key": "properties.instanceId", "type": "str"}, + "create_mode": {"key": "properties.createMode", "type": "str"}, + "restore_parameters": {"key": "properties.restoreParameters", "type": "RestoreParameters"}, + "backup_policy": {"key": "properties.backupPolicy", "type": "BackupPolicy"}, + "cors": {"key": "properties.cors", "type": "[CorsPolicy]"}, + "network_acl_bypass": {"key": "properties.networkAclBypass", "type": "str"}, + "network_acl_bypass_resource_ids": {"key": "properties.networkAclBypassResourceIds", "type": "[str]"}, + "diagnostic_log_settings": {"key": "properties.diagnosticLogSettings", "type": "DiagnosticLogSettings"}, + "disable_local_auth": {"key": "properties.disableLocalAuth", "type": "bool"}, + "capacity": {"key": "properties.capacity", "type": "Capacity"}, + "capacity_mode": {"key": "properties.capacityMode", "type": "str"}, + "capacity_mode_change_transition_state": { + "key": "properties.capacityModeChangeTransitionState", + "type": "CapacityModeChangeTransitionState", + }, + "enable_materialized_views": {"key": "properties.enableMaterializedViews", "type": "bool"}, + "keys_metadata": {"key": "properties.keysMetadata", "type": "DatabaseAccountKeysMetadata"}, + "enable_partition_merge": {"key": "properties.enablePartitionMerge", "type": "bool"}, + "enable_burst_capacity": {"key": "properties.enableBurstCapacity", "type": "bool"}, + "minimal_tls_version": {"key": "properties.minimalTlsVersion", "type": "str"}, + "customer_managed_key_status": {"key": "properties.customerManagedKeyStatus", "type": "str"}, + "enable_priority_based_execution": {"key": "properties.enablePriorityBasedExecution", "type": "bool"}, + "default_priority_level": {"key": "properties.defaultPriorityLevel", "type": "str"}, + "enable_per_region_per_partition_autoscale": { + "key": "properties.enablePerRegionPerPartitionAutoscale", + "type": "bool", + }, + } + + def __init__( # pylint: disable=too-many-locals + self, + *, + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + kind: Optional[Union[str, "_models.DatabaseAccountKind"]] = None, + ip_rules: Optional[List["_models.IpAddressOrRange"]] = None, + is_virtual_network_filter_enabled: Optional[bool] = None, + enable_automatic_failover: Optional[bool] = None, + consistency_policy: Optional["_models.ConsistencyPolicy"] = None, + capabilities: Optional[List["_models.Capability"]] = None, + virtual_network_rules: Optional[List["_models.VirtualNetworkRule"]] = None, + enable_multiple_write_locations: Optional[bool] = None, + enable_cassandra_connector: Optional[bool] = None, + connector_offer: Optional[Union[str, "_models.ConnectorOffer"]] = None, + disable_key_based_metadata_write_access: Optional[bool] = None, + key_vault_key_uri: Optional[str] = None, + default_identity: Optional[str] = None, + public_network_access: Optional[Union[str, "_models.PublicNetworkAccess"]] = None, + enable_free_tier: Optional[bool] = None, + api_properties: Optional["_models.ApiProperties"] = None, + enable_analytical_storage: Optional[bool] = None, + analytical_storage_configuration: Optional["_models.AnalyticalStorageConfiguration"] = None, + create_mode: Union[str, "_models.CreateMode"] = "Default", + restore_parameters: Optional["_models.RestoreParameters"] = None, + backup_policy: Optional["_models.BackupPolicy"] = None, + cors: Optional[List["_models.CorsPolicy"]] = None, + network_acl_bypass: Optional[Union[str, "_models.NetworkAclBypass"]] = None, + network_acl_bypass_resource_ids: Optional[List[str]] = None, + diagnostic_log_settings: Optional["_models.DiagnosticLogSettings"] = None, + disable_local_auth: Optional[bool] = None, + capacity: Optional["_models.Capacity"] = None, + capacity_mode: Optional[Union[str, "_models.CapacityMode"]] = None, + capacity_mode_change_transition_state: Optional["_models.CapacityModeChangeTransitionState"] = None, + enable_materialized_views: Optional[bool] = None, + enable_partition_merge: Optional[bool] = None, + enable_burst_capacity: Optional[bool] = None, + minimal_tls_version: Optional[Union[str, "_models.MinimalTlsVersion"]] = None, + customer_managed_key_status: Optional[str] = None, + enable_priority_based_execution: Optional[bool] = None, + default_priority_level: Optional[Union[str, "_models.DefaultPriorityLevel"]] = None, + enable_per_region_per_partition_autoscale: Optional[bool] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword kind: Indicates the type of database account. This can only be set at database account + creation. Known values are: "GlobalDocumentDB", "MongoDB", and "Parse". + :paramtype kind: str or ~azure.mgmt.cosmosdb.models.DatabaseAccountKind + :keyword ip_rules: List of IpRules. + :paramtype ip_rules: list[~azure.mgmt.cosmosdb.models.IpAddressOrRange] + :keyword is_virtual_network_filter_enabled: Flag to indicate whether to enable/disable Virtual + Network ACL rules. + :paramtype is_virtual_network_filter_enabled: bool + :keyword enable_automatic_failover: Enables automatic failover of the write region in the rare + event that the region is unavailable due to an outage. Automatic failover will result in a new + write region for the account and is chosen based on the failover priorities configured for the + account. + :paramtype enable_automatic_failover: bool + :keyword consistency_policy: The consistency policy for the Cosmos DB database account. + :paramtype consistency_policy: ~azure.mgmt.cosmosdb.models.ConsistencyPolicy + :keyword capabilities: List of Cosmos DB capabilities for the account. + :paramtype capabilities: list[~azure.mgmt.cosmosdb.models.Capability] + :keyword virtual_network_rules: List of Virtual Network ACL rules configured for the Cosmos DB + account. + :paramtype virtual_network_rules: list[~azure.mgmt.cosmosdb.models.VirtualNetworkRule] + :keyword enable_multiple_write_locations: Enables the account to write in multiple locations. + :paramtype enable_multiple_write_locations: bool + :keyword enable_cassandra_connector: Enables the cassandra connector on the Cosmos DB C* + account. + :paramtype enable_cassandra_connector: bool + :keyword connector_offer: The cassandra connector offer type for the Cosmos DB database C* + account. "Small" + :paramtype connector_offer: str or ~azure.mgmt.cosmosdb.models.ConnectorOffer + :keyword disable_key_based_metadata_write_access: Disable write operations on metadata + resources (databases, containers, throughput) via account keys. + :paramtype disable_key_based_metadata_write_access: bool + :keyword key_vault_key_uri: The URI of the key vault. + :paramtype key_vault_key_uri: str + :keyword default_identity: The default identity for accessing key vault used in features like + customer managed keys. The default identity needs to be explicitly set by the users. It can be + "FirstPartyIdentity", "SystemAssignedIdentity" and more. + :paramtype default_identity: str + :keyword public_network_access: Whether requests from Public Network are allowed. Known values + are: "Enabled", "Disabled", and "SecuredByPerimeter". + :paramtype public_network_access: str or ~azure.mgmt.cosmosdb.models.PublicNetworkAccess + :keyword enable_free_tier: Flag to indicate whether Free Tier is enabled. + :paramtype enable_free_tier: bool + :keyword api_properties: API specific properties. + :paramtype api_properties: ~azure.mgmt.cosmosdb.models.ApiProperties + :keyword enable_analytical_storage: Flag to indicate whether to enable storage analytics. + :paramtype enable_analytical_storage: bool + :keyword analytical_storage_configuration: Analytical storage specific properties. + :paramtype analytical_storage_configuration: + ~azure.mgmt.cosmosdb.models.AnalyticalStorageConfiguration + :keyword create_mode: Enum to indicate the mode of account creation. Known values are: + "Default" and "Restore". + :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + :keyword restore_parameters: Parameters to indicate the information about the restore. + :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.RestoreParameters + :keyword backup_policy: The object representing the policy for taking backups on an account. + :paramtype backup_policy: ~azure.mgmt.cosmosdb.models.BackupPolicy + :keyword cors: The CORS policy for the Cosmos DB database account. + :paramtype cors: list[~azure.mgmt.cosmosdb.models.CorsPolicy] + :keyword network_acl_bypass: Indicates what services are allowed to bypass firewall checks. + Known values are: "None" and "AzureServices". + :paramtype network_acl_bypass: str or ~azure.mgmt.cosmosdb.models.NetworkAclBypass + :keyword network_acl_bypass_resource_ids: An array that contains the Resource Ids for Network + Acl Bypass for the Cosmos DB account. + :paramtype network_acl_bypass_resource_ids: list[str] + :keyword diagnostic_log_settings: The Object representing the different Diagnostic log settings + for the Cosmos DB Account. + :paramtype diagnostic_log_settings: ~azure.mgmt.cosmosdb.models.DiagnosticLogSettings + :keyword disable_local_auth: Opt-out of local authentication and ensure only MSI and AAD can be + used exclusively for authentication. + :paramtype disable_local_auth: bool + :keyword capacity: The object that represents all properties related to capacity enforcement on + an account. + :paramtype capacity: ~azure.mgmt.cosmosdb.models.Capacity + :keyword capacity_mode: Indicates the capacityMode of the Cosmos DB account. Known values are: + "None", "Provisioned", and "Serverless". + :paramtype capacity_mode: str or ~azure.mgmt.cosmosdb.models.CapacityMode + :keyword capacity_mode_change_transition_state: The object that represents the migration state + for the CapacityMode of the Cosmos DB account. + :paramtype capacity_mode_change_transition_state: + ~azure.mgmt.cosmosdb.models.CapacityModeChangeTransitionState + :keyword enable_materialized_views: Flag to indicate whether to enable MaterializedViews on the + Cosmos DB account. + :paramtype enable_materialized_views: bool + :keyword enable_partition_merge: Flag to indicate enabling/disabling of Partition Merge feature + on the account. + :paramtype enable_partition_merge: bool + :keyword enable_burst_capacity: Flag to indicate enabling/disabling of Burst Capacity Preview + feature on the account. + :paramtype enable_burst_capacity: bool + :keyword minimal_tls_version: Indicates the minimum allowed Tls version. The default is Tls + 1.0, except for Cassandra and Mongo API's, which only work with Tls 1.2. Known values are: + "Tls", "Tls11", and "Tls12". + :paramtype minimal_tls_version: str or ~azure.mgmt.cosmosdb.models.MinimalTlsVersion + :keyword customer_managed_key_status: Indicates the status of the Customer Managed Key feature + on the account. In case there are errors, the property provides troubleshooting guidance. + :paramtype customer_managed_key_status: str + :keyword enable_priority_based_execution: Flag to indicate enabling/disabling of Priority Based + Execution Preview feature on the account. + :paramtype enable_priority_based_execution: bool + :keyword default_priority_level: Enum to indicate default Priority Level of request for + Priority Based Execution. Known values are: "High" and "Low". + :paramtype default_priority_level: str or ~azure.mgmt.cosmosdb.models.DefaultPriorityLevel + :keyword enable_per_region_per_partition_autoscale: Flag to indicate enabling/disabling of + Per-Region Per-partition autoscale Preview feature on the account. + :paramtype enable_per_region_per_partition_autoscale: bool + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.kind = kind + self.system_data = None + self.provisioning_state = None + self.document_endpoint = None + self.database_account_offer_type = None + self.ip_rules = ip_rules + self.is_virtual_network_filter_enabled = is_virtual_network_filter_enabled + self.enable_automatic_failover = enable_automatic_failover + self.consistency_policy = consistency_policy + self.capabilities = capabilities + self.write_locations = None + self.read_locations = None + self.locations = None + self.failover_policies = None + self.virtual_network_rules = virtual_network_rules + self.private_endpoint_connections = None + self.enable_multiple_write_locations = enable_multiple_write_locations + self.enable_cassandra_connector = enable_cassandra_connector + self.connector_offer = connector_offer + self.disable_key_based_metadata_write_access = disable_key_based_metadata_write_access + self.key_vault_key_uri = key_vault_key_uri + self.default_identity = default_identity + self.public_network_access = public_network_access + self.enable_free_tier = enable_free_tier + self.api_properties = api_properties + self.enable_analytical_storage = enable_analytical_storage + self.analytical_storage_configuration = analytical_storage_configuration + self.instance_id = None + self.create_mode = create_mode + self.restore_parameters = restore_parameters + self.backup_policy = backup_policy + self.cors = cors + self.network_acl_bypass = network_acl_bypass + self.network_acl_bypass_resource_ids = network_acl_bypass_resource_ids + self.diagnostic_log_settings = diagnostic_log_settings + self.disable_local_auth = disable_local_auth + self.capacity = capacity + self.capacity_mode = capacity_mode + self.capacity_mode_change_transition_state = capacity_mode_change_transition_state + self.enable_materialized_views = enable_materialized_views + self.keys_metadata = None + self.enable_partition_merge = enable_partition_merge + self.enable_burst_capacity = enable_burst_capacity + self.minimal_tls_version = minimal_tls_version + self.customer_managed_key_status = customer_managed_key_status + self.enable_priority_based_execution = enable_priority_based_execution + self.default_priority_level = default_priority_level + self.enable_per_region_per_partition_autoscale = enable_per_region_per_partition_autoscale + + +class DatabaseAccountKeysMetadata(_serialization.Model): + """The metadata related to each access key for the given Cosmos DB database account. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar primary_master_key: The metadata related to the Primary Read-Write Key for the given + Cosmos DB database account. + :vartype primary_master_key: ~azure.mgmt.cosmosdb.models.AccountKeyMetadata + :ivar secondary_master_key: The metadata related to the Secondary Read-Write Key for the given + Cosmos DB database account. + :vartype secondary_master_key: ~azure.mgmt.cosmosdb.models.AccountKeyMetadata + :ivar primary_readonly_master_key: The metadata related to the Primary Read-Only Key for the + given Cosmos DB database account. + :vartype primary_readonly_master_key: ~azure.mgmt.cosmosdb.models.AccountKeyMetadata + :ivar secondary_readonly_master_key: The metadata related to the Secondary Read-Only Key for + the given Cosmos DB database account. + :vartype secondary_readonly_master_key: ~azure.mgmt.cosmosdb.models.AccountKeyMetadata + """ + + _validation = { + "primary_master_key": {"readonly": True}, + "secondary_master_key": {"readonly": True}, + "primary_readonly_master_key": {"readonly": True}, + "secondary_readonly_master_key": {"readonly": True}, + } + + _attribute_map = { + "primary_master_key": {"key": "primaryMasterKey", "type": "AccountKeyMetadata"}, + "secondary_master_key": {"key": "secondaryMasterKey", "type": "AccountKeyMetadata"}, + "primary_readonly_master_key": {"key": "primaryReadonlyMasterKey", "type": "AccountKeyMetadata"}, + "secondary_readonly_master_key": {"key": "secondaryReadonlyMasterKey", "type": "AccountKeyMetadata"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.primary_master_key = None + self.secondary_master_key = None + self.primary_readonly_master_key = None + self.secondary_readonly_master_key = None + + +class DatabaseAccountListConnectionStringsResult(_serialization.Model): # pylint: disable=name-too-long + """The connection strings for the given database account. + + :ivar connection_strings: An array that contains the connection strings for the Cosmos DB + account. + :vartype connection_strings: list[~azure.mgmt.cosmosdb.models.DatabaseAccountConnectionString] + """ + + _attribute_map = { + "connection_strings": {"key": "connectionStrings", "type": "[DatabaseAccountConnectionString]"}, + } + + def __init__( + self, *, connection_strings: Optional[List["_models.DatabaseAccountConnectionString"]] = None, **kwargs: Any + ) -> None: + """ + :keyword connection_strings: An array that contains the connection strings for the Cosmos DB + account. + :paramtype connection_strings: + list[~azure.mgmt.cosmosdb.models.DatabaseAccountConnectionString] + """ + super().__init__(**kwargs) + self.connection_strings = connection_strings + + +class DatabaseAccountListReadOnlyKeysResult(_serialization.Model): + """The read-only access keys for the given database account. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar primary_readonly_master_key: Base 64 encoded value of the primary read-only key. + :vartype primary_readonly_master_key: str + :ivar secondary_readonly_master_key: Base 64 encoded value of the secondary read-only key. + :vartype secondary_readonly_master_key: str + """ + + _validation = { + "primary_readonly_master_key": {"readonly": True}, + "secondary_readonly_master_key": {"readonly": True}, + } + + _attribute_map = { + "primary_readonly_master_key": {"key": "primaryReadonlyMasterKey", "type": "str"}, + "secondary_readonly_master_key": {"key": "secondaryReadonlyMasterKey", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.primary_readonly_master_key = None + self.secondary_readonly_master_key = None + + +class DatabaseAccountListKeysResult(DatabaseAccountListReadOnlyKeysResult): + """The access keys for the given database account. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar primary_readonly_master_key: Base 64 encoded value of the primary read-only key. + :vartype primary_readonly_master_key: str + :ivar secondary_readonly_master_key: Base 64 encoded value of the secondary read-only key. + :vartype secondary_readonly_master_key: str + :ivar primary_master_key: Base 64 encoded value of the primary read-write key. + :vartype primary_master_key: str + :ivar secondary_master_key: Base 64 encoded value of the secondary read-write key. + :vartype secondary_master_key: str + """ + + _validation = { + "primary_readonly_master_key": {"readonly": True}, + "secondary_readonly_master_key": {"readonly": True}, + "primary_master_key": {"readonly": True}, + "secondary_master_key": {"readonly": True}, + } + + _attribute_map = { + "primary_readonly_master_key": {"key": "primaryReadonlyMasterKey", "type": "str"}, + "secondary_readonly_master_key": {"key": "secondaryReadonlyMasterKey", "type": "str"}, + "primary_master_key": {"key": "primaryMasterKey", "type": "str"}, + "secondary_master_key": {"key": "secondaryMasterKey", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.primary_master_key = None + self.secondary_master_key = None + + +class DatabaseAccountRegenerateKeyParameters(_serialization.Model): + """Parameters to regenerate the keys within the database account. + + All required parameters must be populated in order to send to server. + + :ivar key_kind: The access key to regenerate. Required. Known values are: "primary", + "secondary", "primaryReadonly", and "secondaryReadonly". + :vartype key_kind: str or ~azure.mgmt.cosmosdb.models.KeyKind + """ + + _validation = { + "key_kind": {"required": True}, + } + + _attribute_map = { + "key_kind": {"key": "keyKind", "type": "str"}, + } + + def __init__(self, *, key_kind: Union[str, "_models.KeyKind"], **kwargs: Any) -> None: + """ + :keyword key_kind: The access key to regenerate. Required. Known values are: "primary", + "secondary", "primaryReadonly", and "secondaryReadonly". + :paramtype key_kind: str or ~azure.mgmt.cosmosdb.models.KeyKind + """ + super().__init__(**kwargs) + self.key_kind = key_kind + + +class DatabaseAccountsListResult(_serialization.Model): + """The List operation response, that contains the database accounts and their properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of database account and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[DatabaseAccountGetResults]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class DatabaseAccountUpdateParameters(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Parameters for patching Azure Cosmos DB database account properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar consistency_policy: The consistency policy for the Cosmos DB account. + :vartype consistency_policy: ~azure.mgmt.cosmosdb.models.ConsistencyPolicy + :ivar locations: An array that contains the georeplication locations enabled for the Cosmos DB + account. + :vartype locations: list[~azure.mgmt.cosmosdb.models.Location] + :ivar ip_rules: List of IpRules. + :vartype ip_rules: list[~azure.mgmt.cosmosdb.models.IpAddressOrRange] + :ivar is_virtual_network_filter_enabled: Flag to indicate whether to enable/disable Virtual + Network ACL rules. + :vartype is_virtual_network_filter_enabled: bool + :ivar enable_automatic_failover: Enables automatic failover of the write region in the rare + event that the region is unavailable due to an outage. Automatic failover will result in a new + write region for the account and is chosen based on the failover priorities configured for the + account. + :vartype enable_automatic_failover: bool + :ivar capabilities: List of Cosmos DB capabilities for the account. + :vartype capabilities: list[~azure.mgmt.cosmosdb.models.Capability] + :ivar virtual_network_rules: List of Virtual Network ACL rules configured for the Cosmos DB + account. + :vartype virtual_network_rules: list[~azure.mgmt.cosmosdb.models.VirtualNetworkRule] + :ivar enable_multiple_write_locations: Enables the account to write in multiple locations. + :vartype enable_multiple_write_locations: bool + :ivar enable_cassandra_connector: Enables the cassandra connector on the Cosmos DB C* account. + :vartype enable_cassandra_connector: bool + :ivar connector_offer: The cassandra connector offer type for the Cosmos DB database C* + account. "Small" + :vartype connector_offer: str or ~azure.mgmt.cosmosdb.models.ConnectorOffer + :ivar disable_key_based_metadata_write_access: Disable write operations on metadata resources + (databases, containers, throughput) via account keys. + :vartype disable_key_based_metadata_write_access: bool + :ivar key_vault_key_uri: The URI of the key vault. + :vartype key_vault_key_uri: str + :ivar default_identity: The default identity for accessing key vault used in features like + customer managed keys. The default identity needs to be explicitly set by the users. It can be + "FirstPartyIdentity", "SystemAssignedIdentity" and more. + :vartype default_identity: str + :ivar public_network_access: Whether requests from Public Network are allowed. Known values + are: "Enabled", "Disabled", and "SecuredByPerimeter". + :vartype public_network_access: str or ~azure.mgmt.cosmosdb.models.PublicNetworkAccess + :ivar enable_free_tier: Flag to indicate whether Free Tier is enabled. + :vartype enable_free_tier: bool + :ivar api_properties: API specific properties. Currently, supported only for MongoDB API. + :vartype api_properties: ~azure.mgmt.cosmosdb.models.ApiProperties + :ivar enable_analytical_storage: Flag to indicate whether to enable storage analytics. + :vartype enable_analytical_storage: bool + :ivar analytical_storage_configuration: Analytical storage specific properties. + :vartype analytical_storage_configuration: + ~azure.mgmt.cosmosdb.models.AnalyticalStorageConfiguration + :ivar backup_policy: The object representing the policy for taking backups on an account. + :vartype backup_policy: ~azure.mgmt.cosmosdb.models.BackupPolicy + :ivar cors: The CORS policy for the Cosmos DB database account. + :vartype cors: list[~azure.mgmt.cosmosdb.models.CorsPolicy] + :ivar network_acl_bypass: Indicates what services are allowed to bypass firewall checks. Known + values are: "None" and "AzureServices". + :vartype network_acl_bypass: str or ~azure.mgmt.cosmosdb.models.NetworkAclBypass + :ivar network_acl_bypass_resource_ids: An array that contains the Resource Ids for Network Acl + Bypass for the Cosmos DB account. + :vartype network_acl_bypass_resource_ids: list[str] + :ivar diagnostic_log_settings: The Object representing the different Diagnostic log settings + for the Cosmos DB Account. + :vartype diagnostic_log_settings: ~azure.mgmt.cosmosdb.models.DiagnosticLogSettings + :ivar disable_local_auth: Opt-out of local authentication and ensure only MSI and AAD can be + used exclusively for authentication. + :vartype disable_local_auth: bool + :ivar capacity: The object that represents all properties related to capacity enforcement on an + account. + :vartype capacity: ~azure.mgmt.cosmosdb.models.Capacity + :ivar capacity_mode: Indicates the capacityMode of the Cosmos DB account. Known values are: + "None", "Provisioned", and "Serverless". + :vartype capacity_mode: str or ~azure.mgmt.cosmosdb.models.CapacityMode + :ivar enable_materialized_views: Flag to indicate whether to enable MaterializedViews on the + Cosmos DB account. + :vartype enable_materialized_views: bool + :ivar keys_metadata: This property is ignored during the update operation, as the metadata is + read-only. The object represents the metadata for the Account Keys of the Cosmos DB account. + :vartype keys_metadata: ~azure.mgmt.cosmosdb.models.DatabaseAccountKeysMetadata + :ivar enable_partition_merge: Flag to indicate enabling/disabling of Partition Merge feature on + the account. + :vartype enable_partition_merge: bool + :ivar enable_burst_capacity: Flag to indicate enabling/disabling of Burst Capacity Preview + feature on the account. + :vartype enable_burst_capacity: bool + :ivar minimal_tls_version: Indicates the minimum allowed Tls version. The default is Tls 1.0, + except for Cassandra and Mongo API's, which only work with Tls 1.2. Known values are: "Tls", + "Tls11", and "Tls12". + :vartype minimal_tls_version: str or ~azure.mgmt.cosmosdb.models.MinimalTlsVersion + :ivar customer_managed_key_status: Indicates the status of the Customer Managed Key feature on + the account. In case there are errors, the property provides troubleshooting guidance. + :vartype customer_managed_key_status: str + :ivar enable_priority_based_execution: Flag to indicate enabling/disabling of Priority Based + Execution Preview feature on the account. + :vartype enable_priority_based_execution: bool + :ivar default_priority_level: Enum to indicate default Priority Level of request for Priority + Based Execution. Known values are: "High" and "Low". + :vartype default_priority_level: str or ~azure.mgmt.cosmosdb.models.DefaultPriorityLevel + :ivar enable_per_region_per_partition_autoscale: Flag to indicate enabling/disabling of + Per-Region Per-partition autoscale Preview feature on the account. + :vartype enable_per_region_per_partition_autoscale: bool + """ + + _validation = { + "keys_metadata": {"readonly": True}, + } + + _attribute_map = { + "tags": {"key": "tags", "type": "{str}"}, + "location": {"key": "location", "type": "str"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "consistency_policy": {"key": "properties.consistencyPolicy", "type": "ConsistencyPolicy"}, + "locations": {"key": "properties.locations", "type": "[Location]"}, + "ip_rules": {"key": "properties.ipRules", "type": "[IpAddressOrRange]"}, + "is_virtual_network_filter_enabled": {"key": "properties.isVirtualNetworkFilterEnabled", "type": "bool"}, + "enable_automatic_failover": {"key": "properties.enableAutomaticFailover", "type": "bool"}, + "capabilities": {"key": "properties.capabilities", "type": "[Capability]"}, + "virtual_network_rules": {"key": "properties.virtualNetworkRules", "type": "[VirtualNetworkRule]"}, + "enable_multiple_write_locations": {"key": "properties.enableMultipleWriteLocations", "type": "bool"}, + "enable_cassandra_connector": {"key": "properties.enableCassandraConnector", "type": "bool"}, + "connector_offer": {"key": "properties.connectorOffer", "type": "str"}, + "disable_key_based_metadata_write_access": { + "key": "properties.disableKeyBasedMetadataWriteAccess", + "type": "bool", + }, + "key_vault_key_uri": {"key": "properties.keyVaultKeyUri", "type": "str"}, + "default_identity": {"key": "properties.defaultIdentity", "type": "str"}, + "public_network_access": {"key": "properties.publicNetworkAccess", "type": "str"}, + "enable_free_tier": {"key": "properties.enableFreeTier", "type": "bool"}, + "api_properties": {"key": "properties.apiProperties", "type": "ApiProperties"}, + "enable_analytical_storage": {"key": "properties.enableAnalyticalStorage", "type": "bool"}, + "analytical_storage_configuration": { + "key": "properties.analyticalStorageConfiguration", + "type": "AnalyticalStorageConfiguration", + }, + "backup_policy": {"key": "properties.backupPolicy", "type": "BackupPolicy"}, + "cors": {"key": "properties.cors", "type": "[CorsPolicy]"}, + "network_acl_bypass": {"key": "properties.networkAclBypass", "type": "str"}, + "network_acl_bypass_resource_ids": {"key": "properties.networkAclBypassResourceIds", "type": "[str]"}, + "diagnostic_log_settings": {"key": "properties.diagnosticLogSettings", "type": "DiagnosticLogSettings"}, + "disable_local_auth": {"key": "properties.disableLocalAuth", "type": "bool"}, + "capacity": {"key": "properties.capacity", "type": "Capacity"}, + "capacity_mode": {"key": "properties.capacityMode", "type": "str"}, + "enable_materialized_views": {"key": "properties.enableMaterializedViews", "type": "bool"}, + "keys_metadata": {"key": "properties.keysMetadata", "type": "DatabaseAccountKeysMetadata"}, + "enable_partition_merge": {"key": "properties.enablePartitionMerge", "type": "bool"}, + "enable_burst_capacity": {"key": "properties.enableBurstCapacity", "type": "bool"}, + "minimal_tls_version": {"key": "properties.minimalTlsVersion", "type": "str"}, + "customer_managed_key_status": {"key": "properties.customerManagedKeyStatus", "type": "str"}, + "enable_priority_based_execution": {"key": "properties.enablePriorityBasedExecution", "type": "bool"}, + "default_priority_level": {"key": "properties.defaultPriorityLevel", "type": "str"}, + "enable_per_region_per_partition_autoscale": { + "key": "properties.enablePerRegionPerPartitionAutoscale", + "type": "bool", + }, + } + + def __init__( # pylint: disable=too-many-locals + self, + *, + tags: Optional[Dict[str, str]] = None, + location: Optional[str] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + consistency_policy: Optional["_models.ConsistencyPolicy"] = None, + locations: Optional[List["_models.Location"]] = None, + ip_rules: Optional[List["_models.IpAddressOrRange"]] = None, + is_virtual_network_filter_enabled: Optional[bool] = None, + enable_automatic_failover: Optional[bool] = None, + capabilities: Optional[List["_models.Capability"]] = None, + virtual_network_rules: Optional[List["_models.VirtualNetworkRule"]] = None, + enable_multiple_write_locations: Optional[bool] = None, + enable_cassandra_connector: Optional[bool] = None, + connector_offer: Optional[Union[str, "_models.ConnectorOffer"]] = None, + disable_key_based_metadata_write_access: Optional[bool] = None, + key_vault_key_uri: Optional[str] = None, + default_identity: Optional[str] = None, + public_network_access: Optional[Union[str, "_models.PublicNetworkAccess"]] = None, + enable_free_tier: Optional[bool] = None, + api_properties: Optional["_models.ApiProperties"] = None, + enable_analytical_storage: Optional[bool] = None, + analytical_storage_configuration: Optional["_models.AnalyticalStorageConfiguration"] = None, + backup_policy: Optional["_models.BackupPolicy"] = None, + cors: Optional[List["_models.CorsPolicy"]] = None, + network_acl_bypass: Optional[Union[str, "_models.NetworkAclBypass"]] = None, + network_acl_bypass_resource_ids: Optional[List[str]] = None, + diagnostic_log_settings: Optional["_models.DiagnosticLogSettings"] = None, + disable_local_auth: Optional[bool] = None, + capacity: Optional["_models.Capacity"] = None, + capacity_mode: Optional[Union[str, "_models.CapacityMode"]] = None, + enable_materialized_views: Optional[bool] = None, + enable_partition_merge: Optional[bool] = None, + enable_burst_capacity: Optional[bool] = None, + minimal_tls_version: Optional[Union[str, "_models.MinimalTlsVersion"]] = None, + customer_managed_key_status: Optional[str] = None, + enable_priority_based_execution: Optional[bool] = None, + default_priority_level: Optional[Union[str, "_models.DefaultPriorityLevel"]] = None, + enable_per_region_per_partition_autoscale: Optional[bool] = None, + **kwargs: Any + ) -> None: + """ + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword consistency_policy: The consistency policy for the Cosmos DB account. + :paramtype consistency_policy: ~azure.mgmt.cosmosdb.models.ConsistencyPolicy + :keyword locations: An array that contains the georeplication locations enabled for the Cosmos + DB account. + :paramtype locations: list[~azure.mgmt.cosmosdb.models.Location] + :keyword ip_rules: List of IpRules. + :paramtype ip_rules: list[~azure.mgmt.cosmosdb.models.IpAddressOrRange] + :keyword is_virtual_network_filter_enabled: Flag to indicate whether to enable/disable Virtual + Network ACL rules. + :paramtype is_virtual_network_filter_enabled: bool + :keyword enable_automatic_failover: Enables automatic failover of the write region in the rare + event that the region is unavailable due to an outage. Automatic failover will result in a new + write region for the account and is chosen based on the failover priorities configured for the + account. + :paramtype enable_automatic_failover: bool + :keyword capabilities: List of Cosmos DB capabilities for the account. + :paramtype capabilities: list[~azure.mgmt.cosmosdb.models.Capability] + :keyword virtual_network_rules: List of Virtual Network ACL rules configured for the Cosmos DB + account. + :paramtype virtual_network_rules: list[~azure.mgmt.cosmosdb.models.VirtualNetworkRule] + :keyword enable_multiple_write_locations: Enables the account to write in multiple locations. + :paramtype enable_multiple_write_locations: bool + :keyword enable_cassandra_connector: Enables the cassandra connector on the Cosmos DB C* + account. + :paramtype enable_cassandra_connector: bool + :keyword connector_offer: The cassandra connector offer type for the Cosmos DB database C* + account. "Small" + :paramtype connector_offer: str or ~azure.mgmt.cosmosdb.models.ConnectorOffer + :keyword disable_key_based_metadata_write_access: Disable write operations on metadata + resources (databases, containers, throughput) via account keys. + :paramtype disable_key_based_metadata_write_access: bool + :keyword key_vault_key_uri: The URI of the key vault. + :paramtype key_vault_key_uri: str + :keyword default_identity: The default identity for accessing key vault used in features like + customer managed keys. The default identity needs to be explicitly set by the users. It can be + "FirstPartyIdentity", "SystemAssignedIdentity" and more. + :paramtype default_identity: str + :keyword public_network_access: Whether requests from Public Network are allowed. Known values + are: "Enabled", "Disabled", and "SecuredByPerimeter". + :paramtype public_network_access: str or ~azure.mgmt.cosmosdb.models.PublicNetworkAccess + :keyword enable_free_tier: Flag to indicate whether Free Tier is enabled. + :paramtype enable_free_tier: bool + :keyword api_properties: API specific properties. Currently, supported only for MongoDB API. + :paramtype api_properties: ~azure.mgmt.cosmosdb.models.ApiProperties + :keyword enable_analytical_storage: Flag to indicate whether to enable storage analytics. + :paramtype enable_analytical_storage: bool + :keyword analytical_storage_configuration: Analytical storage specific properties. + :paramtype analytical_storage_configuration: + ~azure.mgmt.cosmosdb.models.AnalyticalStorageConfiguration + :keyword backup_policy: The object representing the policy for taking backups on an account. + :paramtype backup_policy: ~azure.mgmt.cosmosdb.models.BackupPolicy + :keyword cors: The CORS policy for the Cosmos DB database account. + :paramtype cors: list[~azure.mgmt.cosmosdb.models.CorsPolicy] + :keyword network_acl_bypass: Indicates what services are allowed to bypass firewall checks. + Known values are: "None" and "AzureServices". + :paramtype network_acl_bypass: str or ~azure.mgmt.cosmosdb.models.NetworkAclBypass + :keyword network_acl_bypass_resource_ids: An array that contains the Resource Ids for Network + Acl Bypass for the Cosmos DB account. + :paramtype network_acl_bypass_resource_ids: list[str] + :keyword diagnostic_log_settings: The Object representing the different Diagnostic log settings + for the Cosmos DB Account. + :paramtype diagnostic_log_settings: ~azure.mgmt.cosmosdb.models.DiagnosticLogSettings + :keyword disable_local_auth: Opt-out of local authentication and ensure only MSI and AAD can be + used exclusively for authentication. + :paramtype disable_local_auth: bool + :keyword capacity: The object that represents all properties related to capacity enforcement on + an account. + :paramtype capacity: ~azure.mgmt.cosmosdb.models.Capacity + :keyword capacity_mode: Indicates the capacityMode of the Cosmos DB account. Known values are: + "None", "Provisioned", and "Serverless". + :paramtype capacity_mode: str or ~azure.mgmt.cosmosdb.models.CapacityMode + :keyword enable_materialized_views: Flag to indicate whether to enable MaterializedViews on the + Cosmos DB account. + :paramtype enable_materialized_views: bool + :keyword enable_partition_merge: Flag to indicate enabling/disabling of Partition Merge feature + on the account. + :paramtype enable_partition_merge: bool + :keyword enable_burst_capacity: Flag to indicate enabling/disabling of Burst Capacity Preview + feature on the account. + :paramtype enable_burst_capacity: bool + :keyword minimal_tls_version: Indicates the minimum allowed Tls version. The default is Tls + 1.0, except for Cassandra and Mongo API's, which only work with Tls 1.2. Known values are: + "Tls", "Tls11", and "Tls12". + :paramtype minimal_tls_version: str or ~azure.mgmt.cosmosdb.models.MinimalTlsVersion + :keyword customer_managed_key_status: Indicates the status of the Customer Managed Key feature + on the account. In case there are errors, the property provides troubleshooting guidance. + :paramtype customer_managed_key_status: str + :keyword enable_priority_based_execution: Flag to indicate enabling/disabling of Priority Based + Execution Preview feature on the account. + :paramtype enable_priority_based_execution: bool + :keyword default_priority_level: Enum to indicate default Priority Level of request for + Priority Based Execution. Known values are: "High" and "Low". + :paramtype default_priority_level: str or ~azure.mgmt.cosmosdb.models.DefaultPriorityLevel + :keyword enable_per_region_per_partition_autoscale: Flag to indicate enabling/disabling of + Per-Region Per-partition autoscale Preview feature on the account. + :paramtype enable_per_region_per_partition_autoscale: bool + """ + super().__init__(**kwargs) + self.tags = tags + self.location = location + self.identity = identity + self.consistency_policy = consistency_policy + self.locations = locations + self.ip_rules = ip_rules + self.is_virtual_network_filter_enabled = is_virtual_network_filter_enabled + self.enable_automatic_failover = enable_automatic_failover + self.capabilities = capabilities + self.virtual_network_rules = virtual_network_rules + self.enable_multiple_write_locations = enable_multiple_write_locations + self.enable_cassandra_connector = enable_cassandra_connector + self.connector_offer = connector_offer + self.disable_key_based_metadata_write_access = disable_key_based_metadata_write_access + self.key_vault_key_uri = key_vault_key_uri + self.default_identity = default_identity + self.public_network_access = public_network_access + self.enable_free_tier = enable_free_tier + self.api_properties = api_properties + self.enable_analytical_storage = enable_analytical_storage + self.analytical_storage_configuration = analytical_storage_configuration + self.backup_policy = backup_policy + self.cors = cors + self.network_acl_bypass = network_acl_bypass + self.network_acl_bypass_resource_ids = network_acl_bypass_resource_ids + self.diagnostic_log_settings = diagnostic_log_settings + self.disable_local_auth = disable_local_auth + self.capacity = capacity + self.capacity_mode = capacity_mode + self.enable_materialized_views = enable_materialized_views + self.keys_metadata = None + self.enable_partition_merge = enable_partition_merge + self.enable_burst_capacity = enable_burst_capacity + self.minimal_tls_version = minimal_tls_version + self.customer_managed_key_status = customer_managed_key_status + self.enable_priority_based_execution = enable_priority_based_execution + self.default_priority_level = default_priority_level + self.enable_per_region_per_partition_autoscale = enable_per_region_per_partition_autoscale + + +class DatabaseRestoreResource(_serialization.Model): + """Specific Databases to restore. + + :ivar database_name: The name of the database available for restore. + :vartype database_name: str + :ivar collection_names: The names of the collections available for restore. + :vartype collection_names: list[str] + """ + + _attribute_map = { + "database_name": {"key": "databaseName", "type": "str"}, + "collection_names": {"key": "collectionNames", "type": "[str]"}, + } + + def __init__( + self, *, database_name: Optional[str] = None, collection_names: Optional[List[str]] = None, **kwargs: Any + ) -> None: + """ + :keyword database_name: The name of the database available for restore. + :paramtype database_name: str + :keyword collection_names: The names of the collections available for restore. + :paramtype collection_names: list[str] + """ + super().__init__(**kwargs) + self.database_name = database_name + self.collection_names = collection_names + + +class DataCenterResource(ARMProxyResource): + """A managed Cassandra data center. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the database account. + :vartype id: str + :ivar name: The name of the database account. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar properties: Properties of a managed Cassandra data center. + :vartype properties: ~azure.mgmt.cosmosdb.models.DataCenterResourceProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "properties": {"key": "properties", "type": "DataCenterResourceProperties"}, + } + + def __init__(self, *, properties: Optional["_models.DataCenterResourceProperties"] = None, **kwargs: Any) -> None: + """ + :keyword properties: Properties of a managed Cassandra data center. + :paramtype properties: ~azure.mgmt.cosmosdb.models.DataCenterResourceProperties + """ + super().__init__(**kwargs) + self.properties = properties + + +class DataCenterResourceProperties(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Properties of a managed Cassandra data center. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar provisioning_state: The status of the resource at the time the operation was called. + Known values are: "Creating", "Updating", "Deleting", "Succeeded", "Failed", and "Canceled". + :vartype provisioning_state: str or + ~azure.mgmt.cosmosdb.models.ManagedCassandraProvisioningState + :ivar data_center_location: The region this data center should be created in. + :vartype data_center_location: str + :ivar delegated_subnet_id: Resource id of a subnet the nodes in this data center should have + their network interfaces connected to. The subnet must be in the same region specified in + 'dataCenterLocation' and must be able to route to the subnet specified in the cluster's + 'delegatedManagementSubnetId' property. This resource id will be of the form + '/subscriptions/:code:``/resourceGroups/:code:``/providers/Microsoft.Network/virtualNetworks/:code:``/subnets/:code:``'. + :vartype delegated_subnet_id: str + :ivar node_count: The number of nodes the data center should have. This is the desired number. + After it is set, it may take some time for the data center to be scaled to match. To monitor + the number of nodes and their status, use the fetchNodeStatus method on the cluster. + :vartype node_count: int + :ivar seed_nodes: IP addresses for seed nodes in this data center. This is for reference. + Generally you will want to use the seedNodes property on the cluster, which aggregates the seed + nodes from all data centers in the cluster. + :vartype seed_nodes: list[~azure.mgmt.cosmosdb.models.SeedNode] + :ivar base64_encoded_cassandra_yaml_fragment: A fragment of a cassandra.yaml configuration file + to be included in the cassandra.yaml for all nodes in this data center. The fragment should be + Base64 encoded, and only a subset of keys are allowed. + :vartype base64_encoded_cassandra_yaml_fragment: str + :ivar managed_disk_customer_key_uri: Key uri to use for encryption of managed disks. Ensure the + system assigned identity of the cluster has been assigned appropriate permissions(key + get/wrap/unwrap permissions) on the key. + :vartype managed_disk_customer_key_uri: str + :ivar backup_storage_customer_key_uri: Indicates the Key Uri of the customer key to use for + encryption of the backup storage account. + :vartype backup_storage_customer_key_uri: str + :ivar sku: Virtual Machine SKU used for data centers. Default value is Standard_DS14_v2. + :vartype sku: str + :ivar disk_sku: Disk SKU used for data centers. Default value is P30. + :vartype disk_sku: str + :ivar disk_capacity: Number of disks attached to each node. Default is 4. + :vartype disk_capacity: int + :ivar availability_zone: If the data center has Availability Zone support, apply it to the + Virtual Machine ScaleSet that host the cassandra data center virtual machines. + :vartype availability_zone: bool + :ivar authentication_method_ldap_properties: Ldap authentication method properties. This + feature is in preview. + :vartype authentication_method_ldap_properties: + ~azure.mgmt.cosmosdb.models.AuthenticationMethodLdapProperties + :ivar deallocated: Whether the data center has been deallocated. + :vartype deallocated: bool + :ivar provision_error: Error related to resource provisioning. + :vartype provision_error: ~azure.mgmt.cosmosdb.models.CassandraError + :ivar private_endpoint_ip_address: Ip of the VPN Endpoint for this data center. + :vartype private_endpoint_ip_address: str + """ + + _validation = { + "seed_nodes": {"readonly": True}, + } + + _attribute_map = { + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "data_center_location": {"key": "dataCenterLocation", "type": "str"}, + "delegated_subnet_id": {"key": "delegatedSubnetId", "type": "str"}, + "node_count": {"key": "nodeCount", "type": "int"}, + "seed_nodes": {"key": "seedNodes", "type": "[SeedNode]"}, + "base64_encoded_cassandra_yaml_fragment": {"key": "base64EncodedCassandraYamlFragment", "type": "str"}, + "managed_disk_customer_key_uri": {"key": "managedDiskCustomerKeyUri", "type": "str"}, + "backup_storage_customer_key_uri": {"key": "backupStorageCustomerKeyUri", "type": "str"}, + "sku": {"key": "sku", "type": "str"}, + "disk_sku": {"key": "diskSku", "type": "str"}, + "disk_capacity": {"key": "diskCapacity", "type": "int"}, + "availability_zone": {"key": "availabilityZone", "type": "bool"}, + "authentication_method_ldap_properties": { + "key": "authenticationMethodLdapProperties", + "type": "AuthenticationMethodLdapProperties", + }, + "deallocated": {"key": "deallocated", "type": "bool"}, + "provision_error": {"key": "provisionError", "type": "CassandraError"}, + "private_endpoint_ip_address": {"key": "privateEndpointIpAddress", "type": "str"}, + } + + def __init__( + self, + *, + provisioning_state: Optional[Union[str, "_models.ManagedCassandraProvisioningState"]] = None, + data_center_location: Optional[str] = None, + delegated_subnet_id: Optional[str] = None, + node_count: Optional[int] = None, + base64_encoded_cassandra_yaml_fragment: Optional[str] = None, + managed_disk_customer_key_uri: Optional[str] = None, + backup_storage_customer_key_uri: Optional[str] = None, + sku: Optional[str] = None, + disk_sku: Optional[str] = None, + disk_capacity: Optional[int] = None, + availability_zone: Optional[bool] = None, + authentication_method_ldap_properties: Optional["_models.AuthenticationMethodLdapProperties"] = None, + deallocated: Optional[bool] = None, + provision_error: Optional["_models.CassandraError"] = None, + private_endpoint_ip_address: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword provisioning_state: The status of the resource at the time the operation was called. + Known values are: "Creating", "Updating", "Deleting", "Succeeded", "Failed", and "Canceled". + :paramtype provisioning_state: str or + ~azure.mgmt.cosmosdb.models.ManagedCassandraProvisioningState + :keyword data_center_location: The region this data center should be created in. + :paramtype data_center_location: str + :keyword delegated_subnet_id: Resource id of a subnet the nodes in this data center should have + their network interfaces connected to. The subnet must be in the same region specified in + 'dataCenterLocation' and must be able to route to the subnet specified in the cluster's + 'delegatedManagementSubnetId' property. This resource id will be of the form + '/subscriptions/:code:``/resourceGroups/:code:``/providers/Microsoft.Network/virtualNetworks/:code:``/subnets/:code:``'. + :paramtype delegated_subnet_id: str + :keyword node_count: The number of nodes the data center should have. This is the desired + number. After it is set, it may take some time for the data center to be scaled to match. To + monitor the number of nodes and their status, use the fetchNodeStatus method on the cluster. + :paramtype node_count: int + :keyword base64_encoded_cassandra_yaml_fragment: A fragment of a cassandra.yaml configuration + file to be included in the cassandra.yaml for all nodes in this data center. The fragment + should be Base64 encoded, and only a subset of keys are allowed. + :paramtype base64_encoded_cassandra_yaml_fragment: str + :keyword managed_disk_customer_key_uri: Key uri to use for encryption of managed disks. Ensure + the system assigned identity of the cluster has been assigned appropriate permissions(key + get/wrap/unwrap permissions) on the key. + :paramtype managed_disk_customer_key_uri: str + :keyword backup_storage_customer_key_uri: Indicates the Key Uri of the customer key to use for + encryption of the backup storage account. + :paramtype backup_storage_customer_key_uri: str + :keyword sku: Virtual Machine SKU used for data centers. Default value is Standard_DS14_v2. + :paramtype sku: str + :keyword disk_sku: Disk SKU used for data centers. Default value is P30. + :paramtype disk_sku: str + :keyword disk_capacity: Number of disks attached to each node. Default is 4. + :paramtype disk_capacity: int + :keyword availability_zone: If the data center has Availability Zone support, apply it to the + Virtual Machine ScaleSet that host the cassandra data center virtual machines. + :paramtype availability_zone: bool + :keyword authentication_method_ldap_properties: Ldap authentication method properties. This + feature is in preview. + :paramtype authentication_method_ldap_properties: + ~azure.mgmt.cosmosdb.models.AuthenticationMethodLdapProperties + :keyword deallocated: Whether the data center has been deallocated. + :paramtype deallocated: bool + :keyword provision_error: Error related to resource provisioning. + :paramtype provision_error: ~azure.mgmt.cosmosdb.models.CassandraError + :keyword private_endpoint_ip_address: Ip of the VPN Endpoint for this data center. + :paramtype private_endpoint_ip_address: str + """ + super().__init__(**kwargs) + self.provisioning_state = provisioning_state + self.data_center_location = data_center_location + self.delegated_subnet_id = delegated_subnet_id + self.node_count = node_count + self.seed_nodes = None + self.base64_encoded_cassandra_yaml_fragment = base64_encoded_cassandra_yaml_fragment + self.managed_disk_customer_key_uri = managed_disk_customer_key_uri + self.backup_storage_customer_key_uri = backup_storage_customer_key_uri + self.sku = sku + self.disk_sku = disk_sku + self.disk_capacity = disk_capacity + self.availability_zone = availability_zone + self.authentication_method_ldap_properties = authentication_method_ldap_properties + self.deallocated = deallocated + self.provision_error = provision_error + self.private_endpoint_ip_address = private_endpoint_ip_address + + +class DataTransferJobFeedResults(_serialization.Model): + """The List operation response, that contains the Data Transfer jobs and their properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of Data Transfer jobs and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.DataTransferJobGetResults] + :ivar next_link: URL to get the next set of Data Transfer job list results if there are any. + :vartype next_link: str + """ + + _validation = { + "value": {"readonly": True}, + "next_link": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[DataTransferJobGetResults]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + self.next_link = None + + +class DataTransferJobGetResults(ARMProxyResource): # pylint: disable=too-many-instance-attributes + """A Cosmos DB Data Transfer Job. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the database account. + :vartype id: str + :ivar name: The name of the database account. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar job_name: Job Name. + :vartype job_name: str + :ivar source: Source DataStore details. + :vartype source: ~azure.mgmt.cosmosdb.models.DataTransferDataSourceSink + :ivar destination: Destination DataStore details. + :vartype destination: ~azure.mgmt.cosmosdb.models.DataTransferDataSourceSink + :ivar status: Job Status. + :vartype status: str + :ivar processed_count: Processed Count. + :vartype processed_count: int + :ivar total_count: Total Count. + :vartype total_count: int + :ivar last_updated_utc_time: Last Updated Time (ISO-8601 format). + :vartype last_updated_utc_time: ~datetime.datetime + :ivar worker_count: Worker count. + :vartype worker_count: int + :ivar error: Error response for Faulted job. + :vartype error: ~azure.mgmt.cosmosdb.models.ErrorResponse + :ivar duration: Total Duration of Job. + :vartype duration: str + :ivar mode: Mode of job execution. Known values are: "Offline" and "Online". + :vartype mode: str or ~azure.mgmt.cosmosdb.models.DataTransferJobMode + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "job_name": {"readonly": True}, + "status": {"readonly": True}, + "processed_count": {"readonly": True}, + "total_count": {"readonly": True}, + "last_updated_utc_time": {"readonly": True}, + "worker_count": {"minimum": 0}, + "error": {"readonly": True}, + "duration": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "job_name": {"key": "properties.jobName", "type": "str"}, + "source": {"key": "properties.source", "type": "DataTransferDataSourceSink"}, + "destination": {"key": "properties.destination", "type": "DataTransferDataSourceSink"}, + "status": {"key": "properties.status", "type": "str"}, + "processed_count": {"key": "properties.processedCount", "type": "int"}, + "total_count": {"key": "properties.totalCount", "type": "int"}, + "last_updated_utc_time": {"key": "properties.lastUpdatedUtcTime", "type": "iso-8601"}, + "worker_count": {"key": "properties.workerCount", "type": "int"}, + "error": {"key": "properties.error", "type": "ErrorResponse"}, + "duration": {"key": "properties.duration", "type": "str"}, + "mode": {"key": "properties.mode", "type": "str"}, + } + + def __init__( + self, + *, + source: Optional["_models.DataTransferDataSourceSink"] = None, + destination: Optional["_models.DataTransferDataSourceSink"] = None, + worker_count: Optional[int] = None, + mode: Optional[Union[str, "_models.DataTransferJobMode"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword source: Source DataStore details. + :paramtype source: ~azure.mgmt.cosmosdb.models.DataTransferDataSourceSink + :keyword destination: Destination DataStore details. + :paramtype destination: ~azure.mgmt.cosmosdb.models.DataTransferDataSourceSink + :keyword worker_count: Worker count. + :paramtype worker_count: int + :keyword mode: Mode of job execution. Known values are: "Offline" and "Online". + :paramtype mode: str or ~azure.mgmt.cosmosdb.models.DataTransferJobMode + """ + super().__init__(**kwargs) + self.job_name = None + self.source = source + self.destination = destination + self.status = None + self.processed_count = None + self.total_count = None + self.last_updated_utc_time = None + self.worker_count = worker_count + self.error = None + self.duration = None + self.mode = mode + + +class DataTransferJobProperties(_serialization.Model): # pylint: disable=too-many-instance-attributes + """The properties of a DataTransfer Job. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar job_name: Job Name. + :vartype job_name: str + :ivar source: Source DataStore details. Required. + :vartype source: ~azure.mgmt.cosmosdb.models.DataTransferDataSourceSink + :ivar destination: Destination DataStore details. Required. + :vartype destination: ~azure.mgmt.cosmosdb.models.DataTransferDataSourceSink + :ivar status: Job Status. + :vartype status: str + :ivar processed_count: Processed Count. + :vartype processed_count: int + :ivar total_count: Total Count. + :vartype total_count: int + :ivar last_updated_utc_time: Last Updated Time (ISO-8601 format). + :vartype last_updated_utc_time: ~datetime.datetime + :ivar worker_count: Worker count. + :vartype worker_count: int + :ivar error: Error response for Faulted job. + :vartype error: ~azure.mgmt.cosmosdb.models.ErrorResponse + :ivar duration: Total Duration of Job. + :vartype duration: str + :ivar mode: Mode of job execution. Known values are: "Offline" and "Online". + :vartype mode: str or ~azure.mgmt.cosmosdb.models.DataTransferJobMode + """ + + _validation = { + "job_name": {"readonly": True}, + "source": {"required": True}, + "destination": {"required": True}, + "status": {"readonly": True}, + "processed_count": {"readonly": True}, + "total_count": {"readonly": True}, + "last_updated_utc_time": {"readonly": True}, + "worker_count": {"minimum": 0}, + "error": {"readonly": True}, + "duration": {"readonly": True}, + } + + _attribute_map = { + "job_name": {"key": "jobName", "type": "str"}, + "source": {"key": "source", "type": "DataTransferDataSourceSink"}, + "destination": {"key": "destination", "type": "DataTransferDataSourceSink"}, + "status": {"key": "status", "type": "str"}, + "processed_count": {"key": "processedCount", "type": "int"}, + "total_count": {"key": "totalCount", "type": "int"}, + "last_updated_utc_time": {"key": "lastUpdatedUtcTime", "type": "iso-8601"}, + "worker_count": {"key": "workerCount", "type": "int"}, + "error": {"key": "error", "type": "ErrorResponse"}, + "duration": {"key": "duration", "type": "str"}, + "mode": {"key": "mode", "type": "str"}, + } + + def __init__( + self, + *, + source: "_models.DataTransferDataSourceSink", + destination: "_models.DataTransferDataSourceSink", + worker_count: Optional[int] = None, + mode: Optional[Union[str, "_models.DataTransferJobMode"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword source: Source DataStore details. Required. + :paramtype source: ~azure.mgmt.cosmosdb.models.DataTransferDataSourceSink + :keyword destination: Destination DataStore details. Required. + :paramtype destination: ~azure.mgmt.cosmosdb.models.DataTransferDataSourceSink + :keyword worker_count: Worker count. + :paramtype worker_count: int + :keyword mode: Mode of job execution. Known values are: "Offline" and "Online". + :paramtype mode: str or ~azure.mgmt.cosmosdb.models.DataTransferJobMode + """ + super().__init__(**kwargs) + self.job_name = None + self.source = source + self.destination = destination + self.status = None + self.processed_count = None + self.total_count = None + self.last_updated_utc_time = None + self.worker_count = worker_count + self.error = None + self.duration = None + self.mode = mode + + +class RegionalServiceResource(_serialization.Model): + """Resource for a regional service location. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: The regional service name. + :vartype name: str + :ivar location: The location name. + :vartype location: str + :ivar status: Describes the status of a service. Known values are: "Creating", "Running", + "Updating", "Deleting", "Error", and "Stopped". + :vartype status: str or ~azure.mgmt.cosmosdb.models.ServiceStatus + """ + + _validation = { + "name": {"readonly": True}, + "location": {"readonly": True}, + "status": {"readonly": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "status": {"key": "status", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.name = None + self.location = None + self.status = None + + +class DataTransferRegionalServiceResource(RegionalServiceResource): + """Resource for a regional service location. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: The regional service name. + :vartype name: str + :ivar location: The location name. + :vartype location: str + :ivar status: Describes the status of a service. Known values are: "Creating", "Running", + "Updating", "Deleting", "Error", and "Stopped". + :vartype status: str or ~azure.mgmt.cosmosdb.models.ServiceStatus + """ + + +class DataTransferServiceResource(_serialization.Model): + """Describes the service response property. + + :ivar properties: Properties for DataTransferServiceResource. + :vartype properties: ~azure.mgmt.cosmosdb.models.DataTransferServiceResourceProperties + """ + + _attribute_map = { + "properties": {"key": "properties", "type": "DataTransferServiceResourceProperties"}, + } + + def __init__( + self, *, properties: Optional["_models.DataTransferServiceResourceProperties"] = None, **kwargs: Any + ) -> None: + """ + :keyword properties: Properties for DataTransferServiceResource. + :paramtype properties: ~azure.mgmt.cosmosdb.models.DataTransferServiceResourceProperties + """ + super().__init__(**kwargs) + self.properties = properties + + +class ServiceResourceCreateUpdateProperties(_serialization.Model): + """Properties in ServiceResourceCreateUpdateParameters. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + DataTransferServiceResourceCreateUpdateProperties, + GraphAPIComputeServiceResourceCreateUpdateProperties, + MaterializedViewsBuilderServiceResourceCreateUpdateProperties, + SqlDedicatedGatewayServiceResourceCreateUpdateProperties + + All required parameters must be populated in order to send to server. + + :ivar instance_size: Instance type for the service. Known values are: "Cosmos.D4s", + "Cosmos.D8s", and "Cosmos.D16s". + :vartype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize + :ivar instance_count: Instance count for the service. + :vartype instance_count: int + :ivar service_type: ServiceType for the service. Required. Known values are: + "SqlDedicatedGateway", "DataTransfer", "GraphAPICompute", and "MaterializedViewsBuilder". + :vartype service_type: str or ~azure.mgmt.cosmosdb.models.ServiceType + """ + + _validation = { + "instance_count": {"minimum": 0}, + "service_type": {"required": True}, + } + + _attribute_map = { + "instance_size": {"key": "instanceSize", "type": "str"}, + "instance_count": {"key": "instanceCount", "type": "int"}, + "service_type": {"key": "serviceType", "type": "str"}, + } + + _subtype_map = { + "service_type": { + "DataTransfer": "DataTransferServiceResourceCreateUpdateProperties", + "GraphAPICompute": "GraphAPIComputeServiceResourceCreateUpdateProperties", + "MaterializedViewsBuilder": "MaterializedViewsBuilderServiceResourceCreateUpdateProperties", + "SqlDedicatedGateway": "SqlDedicatedGatewayServiceResourceCreateUpdateProperties", + } + } + + def __init__( + self, + *, + instance_size: Optional[Union[str, "_models.ServiceSize"]] = None, + instance_count: Optional[int] = None, + **kwargs: Any + ) -> None: + """ + :keyword instance_size: Instance type for the service. Known values are: "Cosmos.D4s", + "Cosmos.D8s", and "Cosmos.D16s". + :paramtype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize + :keyword instance_count: Instance count for the service. + :paramtype instance_count: int + """ + super().__init__(**kwargs) + self.instance_size = instance_size + self.instance_count = instance_count + self.service_type: Optional[str] = None + + +class DataTransferServiceResourceCreateUpdateProperties( + ServiceResourceCreateUpdateProperties +): # pylint: disable=name-too-long + """Properties for Create or Update request for DataTransferServiceResource. + + All required parameters must be populated in order to send to server. + + :ivar instance_size: Instance type for the service. Known values are: "Cosmos.D4s", + "Cosmos.D8s", and "Cosmos.D16s". + :vartype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize + :ivar instance_count: Instance count for the service. + :vartype instance_count: int + :ivar service_type: ServiceType for the service. Required. Known values are: + "SqlDedicatedGateway", "DataTransfer", "GraphAPICompute", and "MaterializedViewsBuilder". + :vartype service_type: str or ~azure.mgmt.cosmosdb.models.ServiceType + """ + + _validation = { + "instance_count": {"minimum": 0}, + "service_type": {"required": True}, + } + + _attribute_map = { + "instance_size": {"key": "instanceSize", "type": "str"}, + "instance_count": {"key": "instanceCount", "type": "int"}, + "service_type": {"key": "serviceType", "type": "str"}, + } + + def __init__( + self, + *, + instance_size: Optional[Union[str, "_models.ServiceSize"]] = None, + instance_count: Optional[int] = None, + **kwargs: Any + ) -> None: + """ + :keyword instance_size: Instance type for the service. Known values are: "Cosmos.D4s", + "Cosmos.D8s", and "Cosmos.D16s". + :paramtype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize + :keyword instance_count: Instance count for the service. + :paramtype instance_count: int + """ + super().__init__(instance_size=instance_size, instance_count=instance_count, **kwargs) + self.service_type: str = "DataTransfer" + + +class ServiceResourceProperties(_serialization.Model): + """Services response resource. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + DataTransferServiceResourceProperties, GraphAPIComputeServiceResourceProperties, + MaterializedViewsBuilderServiceResourceProperties, SqlDedicatedGatewayServiceResourceProperties + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar additional_properties: Unmatched properties from the message are deserialized to this + collection. + :vartype additional_properties: dict[str, any] + :ivar creation_time: Time of the last state change (ISO-8601 format). + :vartype creation_time: ~datetime.datetime + :ivar instance_size: Instance type for the service. Known values are: "Cosmos.D4s", + "Cosmos.D8s", and "Cosmos.D16s". + :vartype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize + :ivar instance_count: Instance count for the service. + :vartype instance_count: int + :ivar service_type: ServiceType for the service. Required. Known values are: + "SqlDedicatedGateway", "DataTransfer", "GraphAPICompute", and "MaterializedViewsBuilder". + :vartype service_type: str or ~azure.mgmt.cosmosdb.models.ServiceType + :ivar status: Describes the status of a service. Known values are: "Creating", "Running", + "Updating", "Deleting", "Error", and "Stopped". + :vartype status: str or ~azure.mgmt.cosmosdb.models.ServiceStatus + """ + + _validation = { + "creation_time": {"readonly": True}, + "instance_count": {"minimum": 0}, + "service_type": {"required": True}, + "status": {"readonly": True}, + } + + _attribute_map = { + "additional_properties": {"key": "", "type": "{object}"}, + "creation_time": {"key": "creationTime", "type": "iso-8601"}, + "instance_size": {"key": "instanceSize", "type": "str"}, + "instance_count": {"key": "instanceCount", "type": "int"}, + "service_type": {"key": "serviceType", "type": "str"}, + "status": {"key": "status", "type": "str"}, + } + + _subtype_map = { + "service_type": { + "DataTransfer": "DataTransferServiceResourceProperties", + "GraphAPICompute": "GraphAPIComputeServiceResourceProperties", + "MaterializedViewsBuilder": "MaterializedViewsBuilderServiceResourceProperties", + "SqlDedicatedGateway": "SqlDedicatedGatewayServiceResourceProperties", + } + } + + def __init__( + self, + *, + additional_properties: Optional[Dict[str, Any]] = None, + instance_size: Optional[Union[str, "_models.ServiceSize"]] = None, + instance_count: Optional[int] = None, + **kwargs: Any + ) -> None: + """ + :keyword additional_properties: Unmatched properties from the message are deserialized to this + collection. + :paramtype additional_properties: dict[str, any] + :keyword instance_size: Instance type for the service. Known values are: "Cosmos.D4s", + "Cosmos.D8s", and "Cosmos.D16s". + :paramtype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize + :keyword instance_count: Instance count for the service. + :paramtype instance_count: int + """ + super().__init__(**kwargs) + self.additional_properties = additional_properties + self.creation_time = None + self.instance_size = instance_size + self.instance_count = instance_count + self.service_type: Optional[str] = None + self.status = None + + +class DataTransferServiceResourceProperties(ServiceResourceProperties): + """Properties for DataTransferServiceResource. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar additional_properties: Unmatched properties from the message are deserialized to this + collection. + :vartype additional_properties: dict[str, any] + :ivar creation_time: Time of the last state change (ISO-8601 format). + :vartype creation_time: ~datetime.datetime + :ivar instance_size: Instance type for the service. Known values are: "Cosmos.D4s", + "Cosmos.D8s", and "Cosmos.D16s". + :vartype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize + :ivar instance_count: Instance count for the service. + :vartype instance_count: int + :ivar service_type: ServiceType for the service. Required. Known values are: + "SqlDedicatedGateway", "DataTransfer", "GraphAPICompute", and "MaterializedViewsBuilder". + :vartype service_type: str or ~azure.mgmt.cosmosdb.models.ServiceType + :ivar status: Describes the status of a service. Known values are: "Creating", "Running", + "Updating", "Deleting", "Error", and "Stopped". + :vartype status: str or ~azure.mgmt.cosmosdb.models.ServiceStatus + :ivar locations: An array that contains all of the locations for the service. + :vartype locations: list[~azure.mgmt.cosmosdb.models.DataTransferRegionalServiceResource] + """ + + _validation = { + "creation_time": {"readonly": True}, + "instance_count": {"minimum": 0}, + "service_type": {"required": True}, + "status": {"readonly": True}, + "locations": {"readonly": True}, + } + + _attribute_map = { + "additional_properties": {"key": "", "type": "{object}"}, + "creation_time": {"key": "creationTime", "type": "iso-8601"}, + "instance_size": {"key": "instanceSize", "type": "str"}, + "instance_count": {"key": "instanceCount", "type": "int"}, + "service_type": {"key": "serviceType", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "locations": {"key": "locations", "type": "[DataTransferRegionalServiceResource]"}, + } + + def __init__( + self, + *, + additional_properties: Optional[Dict[str, Any]] = None, + instance_size: Optional[Union[str, "_models.ServiceSize"]] = None, + instance_count: Optional[int] = None, + **kwargs: Any + ) -> None: + """ + :keyword additional_properties: Unmatched properties from the message are deserialized to this + collection. + :paramtype additional_properties: dict[str, any] + :keyword instance_size: Instance type for the service. Known values are: "Cosmos.D4s", + "Cosmos.D8s", and "Cosmos.D16s". + :paramtype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize + :keyword instance_count: Instance count for the service. + :paramtype instance_count: int + """ + super().__init__( + additional_properties=additional_properties, + instance_size=instance_size, + instance_count=instance_count, + **kwargs + ) + self.service_type: str = "DataTransfer" + self.locations = None + + +class DiagnosticLogSettings(_serialization.Model): + """Indicates what diagnostic log settings are to be enabled. + + :ivar enable_full_text_query: Describe the level of detail with which queries are to be logged. + Known values are: "None", "True", and "False". + :vartype enable_full_text_query: str or ~azure.mgmt.cosmosdb.models.EnableFullTextQuery + """ + + _attribute_map = { + "enable_full_text_query": {"key": "enableFullTextQuery", "type": "str"}, + } + + def __init__( + self, *, enable_full_text_query: Optional[Union[str, "_models.EnableFullTextQuery"]] = None, **kwargs: Any + ) -> None: + """ + :keyword enable_full_text_query: Describe the level of detail with which queries are to be + logged. Known values are: "None", "True", and "False". + :paramtype enable_full_text_query: str or ~azure.mgmt.cosmosdb.models.EnableFullTextQuery + """ + super().__init__(**kwargs) + self.enable_full_text_query = enable_full_text_query + + +class ErrorAdditionalInfo(_serialization.Model): + """The resource management error additional info. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: JSON + """ + + _validation = { + "type": {"readonly": True}, + "info": {"readonly": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "info": {"key": "info", "type": "object"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.type = None + self.info = None + + +class ErrorDetail(_serialization.Model): + """The error detail. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.mgmt.cosmosdb.models.ErrorDetail] + :ivar additional_info: The error additional info. + :vartype additional_info: list[~azure.mgmt.cosmosdb.models.ErrorAdditionalInfo] + """ + + _validation = { + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, + } + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorDetail]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.code = None + self.message = None + self.target = None + self.details = None + self.additional_info = None + + +class ErrorResponse(_serialization.Model): + """Error Response. + + :ivar code: Error code. + :vartype code: str + :ivar message: Error message indicating why the operation failed. + :vartype message: str + """ + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + } + + def __init__(self, *, code: Optional[str] = None, message: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword code: Error code. + :paramtype code: str + :keyword message: Error message indicating why the operation failed. + :paramtype message: str + """ + super().__init__(**kwargs) + self.code = code + self.message = message + + +class ErrorResponseAutoGenerated(_serialization.Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed + operations. (This also follows the OData error response format.). + + :ivar error: The error object. + :vartype error: ~azure.mgmt.cosmosdb.models.ErrorDetail + """ + + _attribute_map = { + "error": {"key": "error", "type": "ErrorDetail"}, + } + + def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs: Any) -> None: + """ + :keyword error: The error object. + :paramtype error: ~azure.mgmt.cosmosdb.models.ErrorDetail + """ + super().__init__(**kwargs) + self.error = error + + +class ExcludedPath(_serialization.Model): + """ExcludedPath. + + :ivar path: The path for which the indexing behavior applies to. Index paths typically start + with root and end with wildcard (/path/*). + :vartype path: str + """ + + _attribute_map = { + "path": {"key": "path", "type": "str"}, + } + + def __init__(self, *, path: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword path: The path for which the indexing behavior applies to. Index paths typically start + with root and end with wildcard (/path/*). + :paramtype path: str + """ + super().__init__(**kwargs) + self.path = path + + +class FailoverPolicies(_serialization.Model): + """The list of new failover policies for the failover priority change. + + All required parameters must be populated in order to send to server. + + :ivar failover_policies: List of failover policies. Required. + :vartype failover_policies: list[~azure.mgmt.cosmosdb.models.FailoverPolicy] + """ + + _validation = { + "failover_policies": {"required": True}, + } + + _attribute_map = { + "failover_policies": {"key": "failoverPolicies", "type": "[FailoverPolicy]"}, + } + + def __init__(self, *, failover_policies: List["_models.FailoverPolicy"], **kwargs: Any) -> None: + """ + :keyword failover_policies: List of failover policies. Required. + :paramtype failover_policies: list[~azure.mgmt.cosmosdb.models.FailoverPolicy] + """ + super().__init__(**kwargs) + self.failover_policies = failover_policies + + +class FailoverPolicy(_serialization.Model): + """The failover policy for a given region of a database account. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique identifier of the region in which the database account replicates to. + Example: <accountName>-<locationName>. + :vartype id: str + :ivar location_name: The name of the region in which the database account exists. + :vartype location_name: str + :ivar failover_priority: The failover priority of the region. A failover priority of 0 + indicates a write region. The maximum value for a failover priority = (total number of regions + - 1). Failover priority values must be unique for each of the regions in which the database + account exists. + :vartype failover_priority: int + """ + + _validation = { + "id": {"readonly": True}, + "failover_priority": {"minimum": 0}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "location_name": {"key": "locationName", "type": "str"}, + "failover_priority": {"key": "failoverPriority", "type": "int"}, + } + + def __init__( + self, *, location_name: Optional[str] = None, failover_priority: Optional[int] = None, **kwargs: Any + ) -> None: + """ + :keyword location_name: The name of the region in which the database account exists. + :paramtype location_name: str + :keyword failover_priority: The failover priority of the region. A failover priority of 0 + indicates a write region. The maximum value for a failover priority = (total number of regions + - 1). Failover priority values must be unique for each of the regions in which the database + account exists. + :paramtype failover_priority: int + """ + super().__init__(**kwargs) + self.id = None + self.location_name = location_name + self.failover_priority = failover_priority + + +class GraphAPIComputeRegionalServiceResource(RegionalServiceResource): + """Resource for a regional service location. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: The regional service name. + :vartype name: str + :ivar location: The location name. + :vartype location: str + :ivar status: Describes the status of a service. Known values are: "Creating", "Running", + "Updating", "Deleting", "Error", and "Stopped". + :vartype status: str or ~azure.mgmt.cosmosdb.models.ServiceStatus + :ivar graph_api_compute_endpoint: The regional endpoint for GraphAPICompute. + :vartype graph_api_compute_endpoint: str + """ + + _validation = { + "name": {"readonly": True}, + "location": {"readonly": True}, + "status": {"readonly": True}, + "graph_api_compute_endpoint": {"readonly": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "graph_api_compute_endpoint": {"key": "graphApiComputeEndpoint", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.graph_api_compute_endpoint = None + + +class GraphAPIComputeServiceResource(_serialization.Model): + """Describes the service response property for GraphAPICompute. + + :ivar properties: Properties for GraphAPIComputeServiceResource. + :vartype properties: ~azure.mgmt.cosmosdb.models.GraphAPIComputeServiceResourceProperties + """ + + _attribute_map = { + "properties": {"key": "properties", "type": "GraphAPIComputeServiceResourceProperties"}, + } + + def __init__( + self, *, properties: Optional["_models.GraphAPIComputeServiceResourceProperties"] = None, **kwargs: Any + ) -> None: + """ + :keyword properties: Properties for GraphAPIComputeServiceResource. + :paramtype properties: ~azure.mgmt.cosmosdb.models.GraphAPIComputeServiceResourceProperties + """ + super().__init__(**kwargs) + self.properties = properties + + +class GraphAPIComputeServiceResourceCreateUpdateProperties( + ServiceResourceCreateUpdateProperties +): # pylint: disable=name-too-long + """Properties for Create or Update request for GraphAPIComputeServiceResource. + + All required parameters must be populated in order to send to server. + + :ivar instance_size: Instance type for the service. Known values are: "Cosmos.D4s", + "Cosmos.D8s", and "Cosmos.D16s". + :vartype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize + :ivar instance_count: Instance count for the service. + :vartype instance_count: int + :ivar service_type: ServiceType for the service. Required. Known values are: + "SqlDedicatedGateway", "DataTransfer", "GraphAPICompute", and "MaterializedViewsBuilder". + :vartype service_type: str or ~azure.mgmt.cosmosdb.models.ServiceType + """ + + _validation = { + "instance_count": {"minimum": 0}, + "service_type": {"required": True}, + } + + _attribute_map = { + "instance_size": {"key": "instanceSize", "type": "str"}, + "instance_count": {"key": "instanceCount", "type": "int"}, + "service_type": {"key": "serviceType", "type": "str"}, + } + + def __init__( + self, + *, + instance_size: Optional[Union[str, "_models.ServiceSize"]] = None, + instance_count: Optional[int] = None, + **kwargs: Any + ) -> None: + """ + :keyword instance_size: Instance type for the service. Known values are: "Cosmos.D4s", + "Cosmos.D8s", and "Cosmos.D16s". + :paramtype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize + :keyword instance_count: Instance count for the service. + :paramtype instance_count: int + """ + super().__init__(instance_size=instance_size, instance_count=instance_count, **kwargs) + self.service_type: str = "GraphAPICompute" + + +class GraphAPIComputeServiceResourceProperties(ServiceResourceProperties): + """Properties for GraphAPIComputeServiceResource. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar additional_properties: Unmatched properties from the message are deserialized to this + collection. + :vartype additional_properties: dict[str, any] + :ivar creation_time: Time of the last state change (ISO-8601 format). + :vartype creation_time: ~datetime.datetime + :ivar instance_size: Instance type for the service. Known values are: "Cosmos.D4s", + "Cosmos.D8s", and "Cosmos.D16s". + :vartype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize + :ivar instance_count: Instance count for the service. + :vartype instance_count: int + :ivar service_type: ServiceType for the service. Required. Known values are: + "SqlDedicatedGateway", "DataTransfer", "GraphAPICompute", and "MaterializedViewsBuilder". + :vartype service_type: str or ~azure.mgmt.cosmosdb.models.ServiceType + :ivar status: Describes the status of a service. Known values are: "Creating", "Running", + "Updating", "Deleting", "Error", and "Stopped". + :vartype status: str or ~azure.mgmt.cosmosdb.models.ServiceStatus + :ivar graph_api_compute_endpoint: GraphAPICompute endpoint for the service. + :vartype graph_api_compute_endpoint: str + :ivar locations: An array that contains all of the locations for the service. + :vartype locations: list[~azure.mgmt.cosmosdb.models.GraphAPIComputeRegionalServiceResource] + """ + + _validation = { + "creation_time": {"readonly": True}, + "instance_count": {"minimum": 0}, + "service_type": {"required": True}, + "status": {"readonly": True}, + "locations": {"readonly": True}, + } + + _attribute_map = { + "additional_properties": {"key": "", "type": "{object}"}, + "creation_time": {"key": "creationTime", "type": "iso-8601"}, + "instance_size": {"key": "instanceSize", "type": "str"}, + "instance_count": {"key": "instanceCount", "type": "int"}, + "service_type": {"key": "serviceType", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "graph_api_compute_endpoint": {"key": "graphApiComputeEndpoint", "type": "str"}, + "locations": {"key": "locations", "type": "[GraphAPIComputeRegionalServiceResource]"}, + } + + def __init__( + self, + *, + additional_properties: Optional[Dict[str, Any]] = None, + instance_size: Optional[Union[str, "_models.ServiceSize"]] = None, + instance_count: Optional[int] = None, + graph_api_compute_endpoint: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword additional_properties: Unmatched properties from the message are deserialized to this + collection. + :paramtype additional_properties: dict[str, any] + :keyword instance_size: Instance type for the service. Known values are: "Cosmos.D4s", + "Cosmos.D8s", and "Cosmos.D16s". + :paramtype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize + :keyword instance_count: Instance count for the service. + :paramtype instance_count: int + :keyword graph_api_compute_endpoint: GraphAPICompute endpoint for the service. + :paramtype graph_api_compute_endpoint: str + """ + super().__init__( + additional_properties=additional_properties, + instance_size=instance_size, + instance_count=instance_count, + **kwargs + ) + self.service_type: str = "GraphAPICompute" + self.graph_api_compute_endpoint = graph_api_compute_endpoint + self.locations = None + + +class GraphResource(_serialization.Model): + """Cosmos DB Graph resource object. + + All required parameters must be populated in order to send to server. + + :ivar id: Name of the Cosmos DB Graph. Required. + :vartype id: str + """ + + _validation = { + "id": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + } + + def __init__(self, *, id: str, **kwargs: Any) -> None: # pylint: disable=redefined-builtin + """ + :keyword id: Name of the Cosmos DB Graph. Required. + :paramtype id: str + """ + super().__init__(**kwargs) + self.id = id + + +class GraphResourceCreateUpdateParameters(ARMResourceProperties): + """Parameters to create and update Cosmos DB Graph resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: The standard JSON format of a Graph resource. Required. + :vartype resource: ~azure.mgmt.cosmosdb.models.GraphResource + :ivar options: A key-value pair of options to be applied for the request. This corresponds to + the headers sent with the request. + :vartype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "resource": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "GraphResource"}, + "options": {"key": "properties.options", "type": "CreateUpdateOptions"}, + } + + def __init__( + self, + *, + resource: "_models.GraphResource", + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + options: Optional["_models.CreateUpdateOptions"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: The standard JSON format of a Graph resource. Required. + :paramtype resource: ~azure.mgmt.cosmosdb.models.GraphResource + :keyword options: A key-value pair of options to be applied for the request. This corresponds + to the headers sent with the request. + :paramtype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + self.options = options + + +class GraphResourceGetPropertiesOptions(OptionsResource): + """GraphResourceGetPropertiesOptions. + + :ivar throughput: Value of the Cosmos DB resource throughput or autoscaleSettings. Use the + ThroughputSetting resource when retrieving offer details. + :vartype throughput: int + :ivar autoscale_settings: Specifies the Autoscale settings. + :vartype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettings + """ + + +class GraphResourceGetPropertiesResource(GraphResource): + """GraphResourceGetPropertiesResource. + + All required parameters must be populated in order to send to server. + + :ivar id: Name of the Cosmos DB Graph. Required. + :vartype id: str + """ + + +class GraphResourceGetResults(ARMResourceProperties): + """An Azure Cosmos DB Graph resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: + :vartype resource: ~azure.mgmt.cosmosdb.models.GraphResourceGetPropertiesResource + :ivar options: + :vartype options: ~azure.mgmt.cosmosdb.models.GraphResourceGetPropertiesOptions + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "GraphResourceGetPropertiesResource"}, + "options": {"key": "properties.options", "type": "GraphResourceGetPropertiesOptions"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + resource: Optional["_models.GraphResourceGetPropertiesResource"] = None, + options: Optional["_models.GraphResourceGetPropertiesOptions"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: + :paramtype resource: ~azure.mgmt.cosmosdb.models.GraphResourceGetPropertiesResource + :keyword options: + :paramtype options: ~azure.mgmt.cosmosdb.models.GraphResourceGetPropertiesOptions + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + self.options = options + + +class GraphResourcesListResult(_serialization.Model): + """The List operation response, that contains the Graph resource and their properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of Graph resource and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.GraphResourceGetResults] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[GraphResourceGetResults]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class GremlinDatabaseCreateUpdateParameters(ARMResourceProperties): + """Parameters to create and update Cosmos DB Gremlin database. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: The standard JSON format of a Gremlin database. Required. + :vartype resource: ~azure.mgmt.cosmosdb.models.GremlinDatabaseResource + :ivar options: A key-value pair of options to be applied for the request. This corresponds to + the headers sent with the request. + :vartype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "resource": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "GremlinDatabaseResource"}, + "options": {"key": "properties.options", "type": "CreateUpdateOptions"}, + } + + def __init__( + self, + *, + resource: "_models.GremlinDatabaseResource", + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + options: Optional["_models.CreateUpdateOptions"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: The standard JSON format of a Gremlin database. Required. + :paramtype resource: ~azure.mgmt.cosmosdb.models.GremlinDatabaseResource + :keyword options: A key-value pair of options to be applied for the request. This corresponds + to the headers sent with the request. + :paramtype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + self.options = options + + +class GremlinDatabaseGetPropertiesOptions(OptionsResource): + """GremlinDatabaseGetPropertiesOptions. + + :ivar throughput: Value of the Cosmos DB resource throughput or autoscaleSettings. Use the + ThroughputSetting resource when retrieving offer details. + :vartype throughput: int + :ivar autoscale_settings: Specifies the Autoscale settings. + :vartype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettings + """ + + +class GremlinDatabaseResource(_serialization.Model): + """Cosmos DB Gremlin database resource object. + + All required parameters must be populated in order to send to server. + + :ivar id: Name of the Cosmos DB Gremlin database. Required. + :vartype id: str + :ivar restore_parameters: Parameters to indicate the information about the restore. + :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" + and "Restore". + :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + """ + + _validation = { + "id": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, + "create_mode": {"key": "createMode", "type": "str"}, + } + + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, + create_mode: Union[str, "_models.CreateMode"] = "Default", + **kwargs: Any + ) -> None: + """ + :keyword id: Name of the Cosmos DB Gremlin database. Required. + :paramtype id: str + :keyword restore_parameters: Parameters to indicate the information about the restore. + :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: + "Default" and "Restore". + :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + """ + super().__init__(**kwargs) + self.id = id + self.restore_parameters = restore_parameters + self.create_mode = create_mode + + +class GremlinDatabaseGetPropertiesResource(GremlinDatabaseResource, ExtendedResourceProperties): + """GremlinDatabaseGetPropertiesResource. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar rid: A system generated property. A unique identifier. + :vartype rid: str + :ivar ts: A system generated property that denotes the last updated timestamp of the resource. + :vartype ts: float + :ivar etag: A system generated property representing the resource etag required for optimistic + concurrency control. + :vartype etag: str + :ivar id: Name of the Cosmos DB Gremlin database. Required. + :vartype id: str + :ivar restore_parameters: Parameters to indicate the information about the restore. + :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" + and "Restore". + :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + """ + + _validation = { + "rid": {"readonly": True}, + "ts": {"readonly": True}, + "etag": {"readonly": True}, + "id": {"required": True}, + } + + _attribute_map = { + "rid": {"key": "_rid", "type": "str"}, + "ts": {"key": "_ts", "type": "float"}, + "etag": {"key": "_etag", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, + "create_mode": {"key": "createMode", "type": "str"}, + } + + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, + create_mode: Union[str, "_models.CreateMode"] = "Default", + **kwargs: Any + ) -> None: + """ + :keyword id: Name of the Cosmos DB Gremlin database. Required. + :paramtype id: str + :keyword restore_parameters: Parameters to indicate the information about the restore. + :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: + "Default" and "Restore". + :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + """ + super().__init__(id=id, restore_parameters=restore_parameters, create_mode=create_mode, **kwargs) + self.rid = None + self.ts = None + self.etag = None + self.id = id + self.restore_parameters = restore_parameters + self.create_mode = create_mode + + +class GremlinDatabaseGetResults(ARMResourceProperties): + """An Azure Cosmos DB Gremlin database. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: + :vartype resource: ~azure.mgmt.cosmosdb.models.GremlinDatabaseGetPropertiesResource + :ivar options: + :vartype options: ~azure.mgmt.cosmosdb.models.GremlinDatabaseGetPropertiesOptions + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "GremlinDatabaseGetPropertiesResource"}, + "options": {"key": "properties.options", "type": "GremlinDatabaseGetPropertiesOptions"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + resource: Optional["_models.GremlinDatabaseGetPropertiesResource"] = None, + options: Optional["_models.GremlinDatabaseGetPropertiesOptions"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: + :paramtype resource: ~azure.mgmt.cosmosdb.models.GremlinDatabaseGetPropertiesResource + :keyword options: + :paramtype options: ~azure.mgmt.cosmosdb.models.GremlinDatabaseGetPropertiesOptions + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + self.options = options + + +class GremlinDatabaseListResult(_serialization.Model): + """The List operation response, that contains the Gremlin databases and their properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of Gremlin databases and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[GremlinDatabaseGetResults]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class GremlinDatabaseRestoreResource(_serialization.Model): + """Specific Gremlin Databases to restore. + + :ivar database_name: The name of the gremlin database available for restore. + :vartype database_name: str + :ivar graph_names: The names of the graphs available for restore. + :vartype graph_names: list[str] + """ + + _attribute_map = { + "database_name": {"key": "databaseName", "type": "str"}, + "graph_names": {"key": "graphNames", "type": "[str]"}, + } + + def __init__( + self, *, database_name: Optional[str] = None, graph_names: Optional[List[str]] = None, **kwargs: Any + ) -> None: + """ + :keyword database_name: The name of the gremlin database available for restore. + :paramtype database_name: str + :keyword graph_names: The names of the graphs available for restore. + :paramtype graph_names: list[str] + """ + super().__init__(**kwargs) + self.database_name = database_name + self.graph_names = graph_names + + +class GremlinGraphCreateUpdateParameters(ARMResourceProperties): + """Parameters to create and update Cosmos DB Gremlin graph. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: The standard JSON format of a Gremlin graph. Required. + :vartype resource: ~azure.mgmt.cosmosdb.models.GremlinGraphResource + :ivar options: A key-value pair of options to be applied for the request. This corresponds to + the headers sent with the request. + :vartype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "resource": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "GremlinGraphResource"}, + "options": {"key": "properties.options", "type": "CreateUpdateOptions"}, + } + + def __init__( + self, + *, + resource: "_models.GremlinGraphResource", + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + options: Optional["_models.CreateUpdateOptions"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: The standard JSON format of a Gremlin graph. Required. + :paramtype resource: ~azure.mgmt.cosmosdb.models.GremlinGraphResource + :keyword options: A key-value pair of options to be applied for the request. This corresponds + to the headers sent with the request. + :paramtype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + self.options = options + + +class GremlinGraphGetPropertiesOptions(OptionsResource): + """GremlinGraphGetPropertiesOptions. + + :ivar throughput: Value of the Cosmos DB resource throughput or autoscaleSettings. Use the + ThroughputSetting resource when retrieving offer details. + :vartype throughput: int + :ivar autoscale_settings: Specifies the Autoscale settings. + :vartype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettings + """ + + +class GremlinGraphResource(_serialization.Model): + """Cosmos DB Gremlin graph resource object. + + All required parameters must be populated in order to send to server. + + :ivar id: Name of the Cosmos DB Gremlin graph. Required. + :vartype id: str + :ivar indexing_policy: The configuration of the indexing policy. By default, the indexing is + automatic for all document paths within the graph. + :vartype indexing_policy: ~azure.mgmt.cosmosdb.models.IndexingPolicy + :ivar partition_key: The configuration of the partition key to be used for partitioning data + into multiple partitions. + :vartype partition_key: ~azure.mgmt.cosmosdb.models.ContainerPartitionKey + :ivar default_ttl: Default time to live. + :vartype default_ttl: int + :ivar unique_key_policy: The unique key policy configuration for specifying uniqueness + constraints on documents in the collection in the Azure Cosmos DB service. + :vartype unique_key_policy: ~azure.mgmt.cosmosdb.models.UniqueKeyPolicy + :ivar conflict_resolution_policy: The conflict resolution policy for the graph. + :vartype conflict_resolution_policy: ~azure.mgmt.cosmosdb.models.ConflictResolutionPolicy + :ivar analytical_storage_ttl: Analytical TTL. + :vartype analytical_storage_ttl: int + :ivar restore_parameters: Parameters to indicate the information about the restore. + :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" + and "Restore". + :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + """ + + _validation = { + "id": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "indexing_policy": {"key": "indexingPolicy", "type": "IndexingPolicy"}, + "partition_key": {"key": "partitionKey", "type": "ContainerPartitionKey"}, + "default_ttl": {"key": "defaultTtl", "type": "int"}, + "unique_key_policy": {"key": "uniqueKeyPolicy", "type": "UniqueKeyPolicy"}, + "conflict_resolution_policy": {"key": "conflictResolutionPolicy", "type": "ConflictResolutionPolicy"}, + "analytical_storage_ttl": {"key": "analyticalStorageTtl", "type": "int"}, + "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, + "create_mode": {"key": "createMode", "type": "str"}, + } + + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + indexing_policy: Optional["_models.IndexingPolicy"] = None, + partition_key: Optional["_models.ContainerPartitionKey"] = None, + default_ttl: Optional[int] = None, + unique_key_policy: Optional["_models.UniqueKeyPolicy"] = None, + conflict_resolution_policy: Optional["_models.ConflictResolutionPolicy"] = None, + analytical_storage_ttl: Optional[int] = None, + restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, + create_mode: Union[str, "_models.CreateMode"] = "Default", + **kwargs: Any + ) -> None: + """ + :keyword id: Name of the Cosmos DB Gremlin graph. Required. + :paramtype id: str + :keyword indexing_policy: The configuration of the indexing policy. By default, the indexing is + automatic for all document paths within the graph. + :paramtype indexing_policy: ~azure.mgmt.cosmosdb.models.IndexingPolicy + :keyword partition_key: The configuration of the partition key to be used for partitioning data + into multiple partitions. + :paramtype partition_key: ~azure.mgmt.cosmosdb.models.ContainerPartitionKey + :keyword default_ttl: Default time to live. + :paramtype default_ttl: int + :keyword unique_key_policy: The unique key policy configuration for specifying uniqueness + constraints on documents in the collection in the Azure Cosmos DB service. + :paramtype unique_key_policy: ~azure.mgmt.cosmosdb.models.UniqueKeyPolicy + :keyword conflict_resolution_policy: The conflict resolution policy for the graph. + :paramtype conflict_resolution_policy: ~azure.mgmt.cosmosdb.models.ConflictResolutionPolicy + :keyword analytical_storage_ttl: Analytical TTL. + :paramtype analytical_storage_ttl: int + :keyword restore_parameters: Parameters to indicate the information about the restore. + :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: + "Default" and "Restore". + :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + """ + super().__init__(**kwargs) + self.id = id + self.indexing_policy = indexing_policy + self.partition_key = partition_key + self.default_ttl = default_ttl + self.unique_key_policy = unique_key_policy + self.conflict_resolution_policy = conflict_resolution_policy + self.analytical_storage_ttl = analytical_storage_ttl + self.restore_parameters = restore_parameters + self.create_mode = create_mode + + +class GremlinGraphGetPropertiesResource( + GremlinGraphResource, ExtendedResourceProperties +): # pylint: disable=too-many-instance-attributes + """GremlinGraphGetPropertiesResource. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar rid: A system generated property. A unique identifier. + :vartype rid: str + :ivar ts: A system generated property that denotes the last updated timestamp of the resource. + :vartype ts: float + :ivar etag: A system generated property representing the resource etag required for optimistic + concurrency control. + :vartype etag: str + :ivar id: Name of the Cosmos DB Gremlin graph. Required. + :vartype id: str + :ivar indexing_policy: The configuration of the indexing policy. By default, the indexing is + automatic for all document paths within the graph. + :vartype indexing_policy: ~azure.mgmt.cosmosdb.models.IndexingPolicy + :ivar partition_key: The configuration of the partition key to be used for partitioning data + into multiple partitions. + :vartype partition_key: ~azure.mgmt.cosmosdb.models.ContainerPartitionKey + :ivar default_ttl: Default time to live. + :vartype default_ttl: int + :ivar unique_key_policy: The unique key policy configuration for specifying uniqueness + constraints on documents in the collection in the Azure Cosmos DB service. + :vartype unique_key_policy: ~azure.mgmt.cosmosdb.models.UniqueKeyPolicy + :ivar conflict_resolution_policy: The conflict resolution policy for the graph. + :vartype conflict_resolution_policy: ~azure.mgmt.cosmosdb.models.ConflictResolutionPolicy + :ivar analytical_storage_ttl: Analytical TTL. + :vartype analytical_storage_ttl: int + :ivar restore_parameters: Parameters to indicate the information about the restore. + :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" + and "Restore". + :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + """ + + _validation = { + "rid": {"readonly": True}, + "ts": {"readonly": True}, + "etag": {"readonly": True}, + "id": {"required": True}, + } + + _attribute_map = { + "rid": {"key": "_rid", "type": "str"}, + "ts": {"key": "_ts", "type": "float"}, + "etag": {"key": "_etag", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "indexing_policy": {"key": "indexingPolicy", "type": "IndexingPolicy"}, + "partition_key": {"key": "partitionKey", "type": "ContainerPartitionKey"}, + "default_ttl": {"key": "defaultTtl", "type": "int"}, + "unique_key_policy": {"key": "uniqueKeyPolicy", "type": "UniqueKeyPolicy"}, + "conflict_resolution_policy": {"key": "conflictResolutionPolicy", "type": "ConflictResolutionPolicy"}, + "analytical_storage_ttl": {"key": "analyticalStorageTtl", "type": "int"}, + "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, + "create_mode": {"key": "createMode", "type": "str"}, + } + + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + indexing_policy: Optional["_models.IndexingPolicy"] = None, + partition_key: Optional["_models.ContainerPartitionKey"] = None, + default_ttl: Optional[int] = None, + unique_key_policy: Optional["_models.UniqueKeyPolicy"] = None, + conflict_resolution_policy: Optional["_models.ConflictResolutionPolicy"] = None, + analytical_storage_ttl: Optional[int] = None, + restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, + create_mode: Union[str, "_models.CreateMode"] = "Default", + **kwargs: Any + ) -> None: + """ + :keyword id: Name of the Cosmos DB Gremlin graph. Required. + :paramtype id: str + :keyword indexing_policy: The configuration of the indexing policy. By default, the indexing is + automatic for all document paths within the graph. + :paramtype indexing_policy: ~azure.mgmt.cosmosdb.models.IndexingPolicy + :keyword partition_key: The configuration of the partition key to be used for partitioning data + into multiple partitions. + :paramtype partition_key: ~azure.mgmt.cosmosdb.models.ContainerPartitionKey + :keyword default_ttl: Default time to live. + :paramtype default_ttl: int + :keyword unique_key_policy: The unique key policy configuration for specifying uniqueness + constraints on documents in the collection in the Azure Cosmos DB service. + :paramtype unique_key_policy: ~azure.mgmt.cosmosdb.models.UniqueKeyPolicy + :keyword conflict_resolution_policy: The conflict resolution policy for the graph. + :paramtype conflict_resolution_policy: ~azure.mgmt.cosmosdb.models.ConflictResolutionPolicy + :keyword analytical_storage_ttl: Analytical TTL. + :paramtype analytical_storage_ttl: int + :keyword restore_parameters: Parameters to indicate the information about the restore. + :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: + "Default" and "Restore". + :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + """ + super().__init__( + id=id, + indexing_policy=indexing_policy, + partition_key=partition_key, + default_ttl=default_ttl, + unique_key_policy=unique_key_policy, + conflict_resolution_policy=conflict_resolution_policy, + analytical_storage_ttl=analytical_storage_ttl, + restore_parameters=restore_parameters, + create_mode=create_mode, + **kwargs + ) + self.rid = None + self.ts = None + self.etag = None + self.id = id + self.indexing_policy = indexing_policy + self.partition_key = partition_key + self.default_ttl = default_ttl + self.unique_key_policy = unique_key_policy + self.conflict_resolution_policy = conflict_resolution_policy + self.analytical_storage_ttl = analytical_storage_ttl + self.restore_parameters = restore_parameters + self.create_mode = create_mode + + +class GremlinGraphGetResults(ARMResourceProperties): + """An Azure Cosmos DB Gremlin graph. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: + :vartype resource: ~azure.mgmt.cosmosdb.models.GremlinGraphGetPropertiesResource + :ivar options: + :vartype options: ~azure.mgmt.cosmosdb.models.GremlinGraphGetPropertiesOptions + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "GremlinGraphGetPropertiesResource"}, + "options": {"key": "properties.options", "type": "GremlinGraphGetPropertiesOptions"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + resource: Optional["_models.GremlinGraphGetPropertiesResource"] = None, + options: Optional["_models.GremlinGraphGetPropertiesOptions"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: + :paramtype resource: ~azure.mgmt.cosmosdb.models.GremlinGraphGetPropertiesResource + :keyword options: + :paramtype options: ~azure.mgmt.cosmosdb.models.GremlinGraphGetPropertiesOptions + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + self.options = options + + +class GremlinGraphListResult(_serialization.Model): + """The List operation response, that contains the graphs and their properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of graphs and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.GremlinGraphGetResults] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[GremlinGraphGetResults]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class IncludedPath(_serialization.Model): + """The paths that are included in indexing. + + :ivar path: The path for which the indexing behavior applies to. Index paths typically start + with root and end with wildcard (/path/*). + :vartype path: str + :ivar indexes: List of indexes for this path. + :vartype indexes: list[~azure.mgmt.cosmosdb.models.Indexes] + """ + + _attribute_map = { + "path": {"key": "path", "type": "str"}, + "indexes": {"key": "indexes", "type": "[Indexes]"}, + } + + def __init__( + self, *, path: Optional[str] = None, indexes: Optional[List["_models.Indexes"]] = None, **kwargs: Any + ) -> None: + """ + :keyword path: The path for which the indexing behavior applies to. Index paths typically start + with root and end with wildcard (/path/*). + :paramtype path: str + :keyword indexes: List of indexes for this path. + :paramtype indexes: list[~azure.mgmt.cosmosdb.models.Indexes] + """ + super().__init__(**kwargs) + self.path = path + self.indexes = indexes + + +class Indexes(_serialization.Model): + """The indexes for the path. + + :ivar data_type: The datatype for which the indexing behavior is applied to. Known values are: + "String", "Number", "Point", "Polygon", "LineString", and "MultiPolygon". + :vartype data_type: str or ~azure.mgmt.cosmosdb.models.DataType + :ivar precision: The precision of the index. -1 is maximum precision. + :vartype precision: int + :ivar kind: Indicates the type of index. Known values are: "Hash", "Range", and "Spatial". + :vartype kind: str or ~azure.mgmt.cosmosdb.models.IndexKind + """ + + _attribute_map = { + "data_type": {"key": "dataType", "type": "str"}, + "precision": {"key": "precision", "type": "int"}, + "kind": {"key": "kind", "type": "str"}, + } + + def __init__( + self, + *, + data_type: Union[str, "_models.DataType"] = "String", + precision: Optional[int] = None, + kind: Union[str, "_models.IndexKind"] = "Hash", + **kwargs: Any + ) -> None: + """ + :keyword data_type: The datatype for which the indexing behavior is applied to. Known values + are: "String", "Number", "Point", "Polygon", "LineString", and "MultiPolygon". + :paramtype data_type: str or ~azure.mgmt.cosmosdb.models.DataType + :keyword precision: The precision of the index. -1 is maximum precision. + :paramtype precision: int + :keyword kind: Indicates the type of index. Known values are: "Hash", "Range", and "Spatial". + :paramtype kind: str or ~azure.mgmt.cosmosdb.models.IndexKind + """ + super().__init__(**kwargs) + self.data_type = data_type + self.precision = precision + self.kind = kind + + +class IndexingPolicy(_serialization.Model): + """Cosmos DB indexing policy. + + :ivar automatic: Indicates if the indexing policy is automatic. + :vartype automatic: bool + :ivar indexing_mode: Indicates the indexing mode. Known values are: "consistent", "lazy", and + "none". + :vartype indexing_mode: str or ~azure.mgmt.cosmosdb.models.IndexingMode + :ivar included_paths: List of paths to include in the indexing. + :vartype included_paths: list[~azure.mgmt.cosmosdb.models.IncludedPath] + :ivar excluded_paths: List of paths to exclude from indexing. + :vartype excluded_paths: list[~azure.mgmt.cosmosdb.models.ExcludedPath] + :ivar composite_indexes: List of composite path list. + :vartype composite_indexes: list[list[~azure.mgmt.cosmosdb.models.CompositePath]] + :ivar spatial_indexes: List of spatial specifics. + :vartype spatial_indexes: list[~azure.mgmt.cosmosdb.models.SpatialSpec] + """ + + _attribute_map = { + "automatic": {"key": "automatic", "type": "bool"}, + "indexing_mode": {"key": "indexingMode", "type": "str"}, + "included_paths": {"key": "includedPaths", "type": "[IncludedPath]"}, + "excluded_paths": {"key": "excludedPaths", "type": "[ExcludedPath]"}, + "composite_indexes": {"key": "compositeIndexes", "type": "[[CompositePath]]"}, + "spatial_indexes": {"key": "spatialIndexes", "type": "[SpatialSpec]"}, + } + + def __init__( + self, + *, + automatic: Optional[bool] = None, + indexing_mode: Union[str, "_models.IndexingMode"] = "consistent", + included_paths: Optional[List["_models.IncludedPath"]] = None, + excluded_paths: Optional[List["_models.ExcludedPath"]] = None, + composite_indexes: Optional[List[List["_models.CompositePath"]]] = None, + spatial_indexes: Optional[List["_models.SpatialSpec"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword automatic: Indicates if the indexing policy is automatic. + :paramtype automatic: bool + :keyword indexing_mode: Indicates the indexing mode. Known values are: "consistent", "lazy", + and "none". + :paramtype indexing_mode: str or ~azure.mgmt.cosmosdb.models.IndexingMode + :keyword included_paths: List of paths to include in the indexing. + :paramtype included_paths: list[~azure.mgmt.cosmosdb.models.IncludedPath] + :keyword excluded_paths: List of paths to exclude from indexing. + :paramtype excluded_paths: list[~azure.mgmt.cosmosdb.models.ExcludedPath] + :keyword composite_indexes: List of composite path list. + :paramtype composite_indexes: list[list[~azure.mgmt.cosmosdb.models.CompositePath]] + :keyword spatial_indexes: List of spatial specifics. + :paramtype spatial_indexes: list[~azure.mgmt.cosmosdb.models.SpatialSpec] + """ + super().__init__(**kwargs) + self.automatic = automatic + self.indexing_mode = indexing_mode + self.included_paths = included_paths + self.excluded_paths = excluded_paths + self.composite_indexes = composite_indexes + self.spatial_indexes = spatial_indexes + + +class IpAddressOrRange(_serialization.Model): + """IpAddressOrRange object. + + :ivar ip_address_or_range: A single IPv4 address or a single IPv4 address range in CIDR format. + Provided IPs must be well-formatted and cannot be contained in one of the following ranges: + 10.0.0.0/8, 100.64.0.0/10, 172.16.0.0/12, 192.168.0.0/16, since these are not enforceable by + the IP address filter. Example of valid inputs: “23.40.210.245” or “23.40.210.0/8”. + :vartype ip_address_or_range: str + """ + + _attribute_map = { + "ip_address_or_range": {"key": "ipAddressOrRange", "type": "str"}, + } + + def __init__(self, *, ip_address_or_range: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword ip_address_or_range: A single IPv4 address or a single IPv4 address range in CIDR + format. Provided IPs must be well-formatted and cannot be contained in one of the following + ranges: 10.0.0.0/8, 100.64.0.0/10, 172.16.0.0/12, 192.168.0.0/16, since these are not + enforceable by the IP address filter. Example of valid inputs: “23.40.210.245” or + “23.40.210.0/8”. + :paramtype ip_address_or_range: str + """ + super().__init__(**kwargs) + self.ip_address_or_range = ip_address_or_range + + +class KeyWrapMetadata(_serialization.Model): + """Represents key wrap metadata that a key wrapping provider can use to wrap/unwrap a client + encryption key. + + :ivar name: The name of associated KeyEncryptionKey (aka CustomerManagedKey). + :vartype name: str + :ivar type: ProviderName of KeyStoreProvider. + :vartype type: str + :ivar value: Reference / link to the KeyEncryptionKey. + :vartype value: str + :ivar algorithm: Algorithm used in wrapping and unwrapping of the data encryption key. + :vartype algorithm: str + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "value": {"key": "value", "type": "str"}, + "algorithm": {"key": "algorithm", "type": "str"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + type: Optional[str] = None, + value: Optional[str] = None, + algorithm: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: The name of associated KeyEncryptionKey (aka CustomerManagedKey). + :paramtype name: str + :keyword type: ProviderName of KeyStoreProvider. + :paramtype type: str + :keyword value: Reference / link to the KeyEncryptionKey. + :paramtype value: str + :keyword algorithm: Algorithm used in wrapping and unwrapping of the data encryption key. + :paramtype algorithm: str + """ + super().__init__(**kwargs) + self.name = name + self.type = type + self.value = value + self.algorithm = algorithm + + +class ListBackups(_serialization.Model): + """List of restorable backups for a Cassandra cluster. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: Container for array of backups. + :vartype value: list[~azure.mgmt.cosmosdb.models.BackupResource] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[BackupResource]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class ListClusters(_serialization.Model): + """List of managed Cassandra clusters. + + :ivar value: Container for the array of clusters. + :vartype value: list[~azure.mgmt.cosmosdb.models.ClusterResource] + """ + + _attribute_map = { + "value": {"key": "value", "type": "[ClusterResource]"}, + } + + def __init__(self, *, value: Optional[List["_models.ClusterResource"]] = None, **kwargs: Any) -> None: + """ + :keyword value: Container for the array of clusters. + :paramtype value: list[~azure.mgmt.cosmosdb.models.ClusterResource] + """ + super().__init__(**kwargs) + self.value = value + + +class ListCommands(_serialization.Model): + """List of commands for cluster. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: Container for array of commands. + :vartype value: list[~azure.mgmt.cosmosdb.models.CommandPublicResource] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[CommandPublicResource]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class ListDataCenters(_serialization.Model): + """List of managed Cassandra data centers and their properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: Container for array of data centers. + :vartype value: list[~azure.mgmt.cosmosdb.models.DataCenterResource] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[DataCenterResource]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class Location(_serialization.Model): + """A region in which the Azure Cosmos DB database account is deployed. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique identifier of the region within the database account. Example: + <accountName>-<locationName>. + :vartype id: str + :ivar location_name: The name of the region. + :vartype location_name: str + :ivar document_endpoint: The connection endpoint for the specific region. Example: + https://<accountName>-<locationName>.documents.azure.com:443/. + :vartype document_endpoint: str + :ivar provisioning_state: The status of the Cosmos DB account at the time the operation was + called. The status can be one of following. 'Creating' – the Cosmos DB account is being + created. When an account is in Creating state, only properties that are specified as input for + the Create Cosmos DB account operation are returned. 'Succeeded' – the Cosmos DB account is + active for use. 'Updating' – the Cosmos DB account is being updated. 'Deleting' – the Cosmos DB + account is being deleted. 'Failed' – the Cosmos DB account failed creation. 'DeletionFailed' – + the Cosmos DB account deletion failed. + :vartype provisioning_state: str + :ivar failover_priority: The failover priority of the region. A failover priority of 0 + indicates a write region. The maximum value for a failover priority = (total number of regions + - 1). Failover priority values must be unique for each of the regions in which the database + account exists. + :vartype failover_priority: int + :ivar is_zone_redundant: Flag to indicate whether or not this region is an AvailabilityZone + region. + :vartype is_zone_redundant: bool + """ + + _validation = { + "id": {"readonly": True}, + "document_endpoint": {"readonly": True}, + "provisioning_state": {"readonly": True}, + "failover_priority": {"minimum": 0}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "location_name": {"key": "locationName", "type": "str"}, + "document_endpoint": {"key": "documentEndpoint", "type": "str"}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "failover_priority": {"key": "failoverPriority", "type": "int"}, + "is_zone_redundant": {"key": "isZoneRedundant", "type": "bool"}, + } + + def __init__( + self, + *, + location_name: Optional[str] = None, + failover_priority: Optional[int] = None, + is_zone_redundant: Optional[bool] = None, + **kwargs: Any + ) -> None: + """ + :keyword location_name: The name of the region. + :paramtype location_name: str + :keyword failover_priority: The failover priority of the region. A failover priority of 0 + indicates a write region. The maximum value for a failover priority = (total number of regions + - 1). Failover priority values must be unique for each of the regions in which the database + account exists. + :paramtype failover_priority: int + :keyword is_zone_redundant: Flag to indicate whether or not this region is an AvailabilityZone + region. + :paramtype is_zone_redundant: bool + """ + super().__init__(**kwargs) + self.id = None + self.location_name = location_name + self.document_endpoint = None + self.provisioning_state = None + self.failover_priority = failover_priority + self.is_zone_redundant = is_zone_redundant + + +class LocationGetResult(ARMProxyResource): + """Cosmos DB location get result. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the database account. + :vartype id: str + :ivar name: The name of the database account. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar properties: Cosmos DB location metadata. + :vartype properties: ~azure.mgmt.cosmosdb.models.LocationProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "properties": {"key": "properties", "type": "LocationProperties"}, + } + + def __init__(self, *, properties: Optional["_models.LocationProperties"] = None, **kwargs: Any) -> None: + """ + :keyword properties: Cosmos DB location metadata. + :paramtype properties: ~azure.mgmt.cosmosdb.models.LocationProperties + """ + super().__init__(**kwargs) + self.properties = properties + + +class LocationListResult(_serialization.Model): + """The List operation response, that contains Cosmos DB locations and their properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of Cosmos DB locations and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.LocationGetResult] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[LocationGetResult]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class LocationProperties(_serialization.Model): + """Cosmos DB location metadata. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar supports_availability_zone: Flag indicating whether the location supports availability + zones or not. + :vartype supports_availability_zone: bool + :ivar is_residency_restricted: Flag indicating whether the location is residency sensitive. + :vartype is_residency_restricted: bool + :ivar backup_storage_redundancies: The properties of available backup storage redundancies. + :vartype backup_storage_redundancies: list[str or + ~azure.mgmt.cosmosdb.models.BackupStorageRedundancy] + :ivar is_subscription_region_access_allowed_for_regular: Flag indicating whether the + subscription have access in region for Non-Availability Zones. + :vartype is_subscription_region_access_allowed_for_regular: bool + :ivar is_subscription_region_access_allowed_for_az: Flag indicating whether the subscription + have access in region for Availability Zones(Az). + :vartype is_subscription_region_access_allowed_for_az: bool + :ivar status: Enum to indicate current buildout status of the region. Known values are: + "Uninitialized", "Initializing", "InternallyReady", "Online", "Deleting", "Succeeded", + "Failed", "Canceled", and "Updating". + :vartype status: str or ~azure.mgmt.cosmosdb.models.Status + """ + + _validation = { + "supports_availability_zone": {"readonly": True}, + "is_residency_restricted": {"readonly": True}, + "backup_storage_redundancies": {"readonly": True}, + "is_subscription_region_access_allowed_for_regular": {"readonly": True}, + "is_subscription_region_access_allowed_for_az": {"readonly": True}, + "status": {"readonly": True}, + } + + _attribute_map = { + "supports_availability_zone": {"key": "supportsAvailabilityZone", "type": "bool"}, + "is_residency_restricted": {"key": "isResidencyRestricted", "type": "bool"}, + "backup_storage_redundancies": {"key": "backupStorageRedundancies", "type": "[str]"}, + "is_subscription_region_access_allowed_for_regular": { + "key": "isSubscriptionRegionAccessAllowedForRegular", + "type": "bool", + }, + "is_subscription_region_access_allowed_for_az": { + "key": "isSubscriptionRegionAccessAllowedForAz", + "type": "bool", + }, + "status": {"key": "status", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.supports_availability_zone = None + self.is_residency_restricted = None + self.backup_storage_redundancies = None + self.is_subscription_region_access_allowed_for_regular = None + self.is_subscription_region_access_allowed_for_az = None + self.status = None + + +class ManagedCassandraManagedServiceIdentity(_serialization.Model): + """Identity for the resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar principal_id: The object id of the identity resource. + :vartype principal_id: str + :ivar tenant_id: The tenant id of the resource. + :vartype tenant_id: str + :ivar type: The type of the resource. Known values are: "SystemAssigned" and "None". + :vartype type: str or ~azure.mgmt.cosmosdb.models.ManagedCassandraResourceIdentityType + """ + + _validation = { + "principal_id": {"readonly": True}, + "tenant_id": {"readonly": True}, + } + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "tenant_id": {"key": "tenantId", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__( + self, *, type: Optional[Union[str, "_models.ManagedCassandraResourceIdentityType"]] = None, **kwargs: Any + ) -> None: + """ + :keyword type: The type of the resource. Known values are: "SystemAssigned" and "None". + :paramtype type: str or ~azure.mgmt.cosmosdb.models.ManagedCassandraResourceIdentityType + """ + super().__init__(**kwargs) + self.principal_id = None + self.tenant_id = None + self.type = type + + +class ManagedCassandraReaperStatus(_serialization.Model): + """ManagedCassandraReaperStatus. + + :ivar healthy: + :vartype healthy: bool + :ivar repair_run_ids: Dictionary of :code:``. + :vartype repair_run_ids: dict[str, str] + :ivar repair_schedules: Dictionary of :code:``. + :vartype repair_schedules: dict[str, str] + """ + + _attribute_map = { + "healthy": {"key": "healthy", "type": "bool"}, + "repair_run_ids": {"key": "repairRunIds", "type": "{str}"}, + "repair_schedules": {"key": "repairSchedules", "type": "{str}"}, + } + + def __init__( + self, + *, + healthy: Optional[bool] = None, + repair_run_ids: Optional[Dict[str, str]] = None, + repair_schedules: Optional[Dict[str, str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword healthy: + :paramtype healthy: bool + :keyword repair_run_ids: Dictionary of :code:``. + :paramtype repair_run_ids: dict[str, str] + :keyword repair_schedules: Dictionary of :code:``. + :paramtype repair_schedules: dict[str, str] + """ + super().__init__(**kwargs) + self.healthy = healthy + self.repair_run_ids = repair_run_ids + self.repair_schedules = repair_schedules + + +class ManagedServiceIdentity(_serialization.Model): + """Identity for the resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar principal_id: The principal id of the system assigned identity. This property will only + be provided for a system assigned identity. + :vartype principal_id: str + :ivar tenant_id: The tenant id of the system assigned identity. This property will only be + provided for a system assigned identity. + :vartype tenant_id: str + :ivar type: The type of identity used for the resource. The type 'SystemAssigned,UserAssigned' + includes both an implicitly created identity and a set of user assigned identities. The type + 'None' will remove any identities from the service. Known values are: "SystemAssigned", + "UserAssigned", "SystemAssigned,UserAssigned", and "None". + :vartype type: str or ~azure.mgmt.cosmosdb.models.ResourceIdentityType + :ivar user_assigned_identities: The list of user identities associated with resource. The user + identity dictionary key references will be ARM resource ids in the form: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. # pylint: disable=line-too-long + :vartype user_assigned_identities: dict[str, + ~azure.mgmt.cosmosdb.models.ManagedServiceIdentityUserAssignedIdentity] + """ + + _validation = { + "principal_id": {"readonly": True}, + "tenant_id": {"readonly": True}, + } + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "tenant_id": {"key": "tenantId", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "user_assigned_identities": { + "key": "userAssignedIdentities", + "type": "{ManagedServiceIdentityUserAssignedIdentity}", + }, + } + + def __init__( + self, + *, + type: Optional[Union[str, "_models.ResourceIdentityType"]] = None, + user_assigned_identities: Optional[Dict[str, "_models.ManagedServiceIdentityUserAssignedIdentity"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword type: The type of identity used for the resource. The type + 'SystemAssigned,UserAssigned' includes both an implicitly created identity and a set of user + assigned identities. The type 'None' will remove any identities from the service. Known values + are: "SystemAssigned", "UserAssigned", "SystemAssigned,UserAssigned", and "None". + :paramtype type: str or ~azure.mgmt.cosmosdb.models.ResourceIdentityType + :keyword user_assigned_identities: The list of user identities associated with resource. The + user identity dictionary key references will be ARM resource ids in the form: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. # pylint: disable=line-too-long + :paramtype user_assigned_identities: dict[str, + ~azure.mgmt.cosmosdb.models.ManagedServiceIdentityUserAssignedIdentity] + """ + super().__init__(**kwargs) + self.principal_id = None + self.tenant_id = None + self.type = type + self.user_assigned_identities = user_assigned_identities + + +class ManagedServiceIdentityUserAssignedIdentity(_serialization.Model): # pylint: disable=name-too-long + """ManagedServiceIdentityUserAssignedIdentity. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar principal_id: The principal id of user assigned identity. + :vartype principal_id: str + :ivar client_id: The client id of user assigned identity. + :vartype client_id: str + """ + + _validation = { + "principal_id": {"readonly": True}, + "client_id": {"readonly": True}, + } + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "client_id": {"key": "clientId", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.principal_id = None + self.client_id = None + + +class MaterializedViewDefinition(_serialization.Model): + """Materialized View definition for the container. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar source_collection_rid: An unique identifier for the source collection. This is a system + generated property. + :vartype source_collection_rid: str + :ivar source_collection_id: The name of the source container on which the Materialized View + will be created. Required. + :vartype source_collection_id: str + :ivar definition: The definition should be an SQL query which would be used to fetch data from + the source container to populate into the Materialized View container. Required. + :vartype definition: str + """ + + _validation = { + "source_collection_rid": {"readonly": True}, + "source_collection_id": {"required": True}, + "definition": {"required": True}, + } + + _attribute_map = { + "source_collection_rid": {"key": "sourceCollectionRid", "type": "str"}, + "source_collection_id": {"key": "sourceCollectionId", "type": "str"}, + "definition": {"key": "definition", "type": "str"}, + } + + def __init__(self, *, source_collection_id: str, definition: str, **kwargs: Any) -> None: + """ + :keyword source_collection_id: The name of the source container on which the Materialized View + will be created. Required. + :paramtype source_collection_id: str + :keyword definition: The definition should be an SQL query which would be used to fetch data + from the source container to populate into the Materialized View container. Required. + :paramtype definition: str + """ + super().__init__(**kwargs) + self.source_collection_rid = None + self.source_collection_id = source_collection_id + self.definition = definition + + +class MaterializedViewsBuilderRegionalServiceResource(RegionalServiceResource): # pylint: disable=name-too-long + """Resource for a regional service location. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: The regional service name. + :vartype name: str + :ivar location: The location name. + :vartype location: str + :ivar status: Describes the status of a service. Known values are: "Creating", "Running", + "Updating", "Deleting", "Error", and "Stopped". + :vartype status: str or ~azure.mgmt.cosmosdb.models.ServiceStatus + """ + + +class MaterializedViewsBuilderServiceResource(_serialization.Model): + """Describes the service response property for MaterializedViewsBuilder. + + :ivar properties: Properties for MaterializedViewsBuilderServiceResource. + :vartype properties: + ~azure.mgmt.cosmosdb.models.MaterializedViewsBuilderServiceResourceProperties + """ + + _attribute_map = { + "properties": {"key": "properties", "type": "MaterializedViewsBuilderServiceResourceProperties"}, + } + + def __init__( + self, *, properties: Optional["_models.MaterializedViewsBuilderServiceResourceProperties"] = None, **kwargs: Any + ) -> None: + """ + :keyword properties: Properties for MaterializedViewsBuilderServiceResource. + :paramtype properties: + ~azure.mgmt.cosmosdb.models.MaterializedViewsBuilderServiceResourceProperties + """ + super().__init__(**kwargs) + self.properties = properties + + +class MaterializedViewsBuilderServiceResourceCreateUpdateProperties( + ServiceResourceCreateUpdateProperties +): # pylint: disable=name-too-long + """Properties for Create or Update request for MaterializedViewsBuilderServiceResource. + + All required parameters must be populated in order to send to server. + + :ivar instance_size: Instance type for the service. Known values are: "Cosmos.D4s", + "Cosmos.D8s", and "Cosmos.D16s". + :vartype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize + :ivar instance_count: Instance count for the service. + :vartype instance_count: int + :ivar service_type: ServiceType for the service. Required. Known values are: + "SqlDedicatedGateway", "DataTransfer", "GraphAPICompute", and "MaterializedViewsBuilder". + :vartype service_type: str or ~azure.mgmt.cosmosdb.models.ServiceType + """ + + _validation = { + "instance_count": {"minimum": 0}, + "service_type": {"required": True}, + } + + _attribute_map = { + "instance_size": {"key": "instanceSize", "type": "str"}, + "instance_count": {"key": "instanceCount", "type": "int"}, + "service_type": {"key": "serviceType", "type": "str"}, + } + + def __init__( + self, + *, + instance_size: Optional[Union[str, "_models.ServiceSize"]] = None, + instance_count: Optional[int] = None, + **kwargs: Any + ) -> None: + """ + :keyword instance_size: Instance type for the service. Known values are: "Cosmos.D4s", + "Cosmos.D8s", and "Cosmos.D16s". + :paramtype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize + :keyword instance_count: Instance count for the service. + :paramtype instance_count: int + """ + super().__init__(instance_size=instance_size, instance_count=instance_count, **kwargs) + self.service_type: str = "MaterializedViewsBuilder" + + +class MaterializedViewsBuilderServiceResourceProperties(ServiceResourceProperties): # pylint: disable=name-too-long + """Properties for MaterializedViewsBuilderServiceResource. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar additional_properties: Unmatched properties from the message are deserialized to this + collection. + :vartype additional_properties: dict[str, any] + :ivar creation_time: Time of the last state change (ISO-8601 format). + :vartype creation_time: ~datetime.datetime + :ivar instance_size: Instance type for the service. Known values are: "Cosmos.D4s", + "Cosmos.D8s", and "Cosmos.D16s". + :vartype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize + :ivar instance_count: Instance count for the service. + :vartype instance_count: int + :ivar service_type: ServiceType for the service. Required. Known values are: + "SqlDedicatedGateway", "DataTransfer", "GraphAPICompute", and "MaterializedViewsBuilder". + :vartype service_type: str or ~azure.mgmt.cosmosdb.models.ServiceType + :ivar status: Describes the status of a service. Known values are: "Creating", "Running", + "Updating", "Deleting", "Error", and "Stopped". + :vartype status: str or ~azure.mgmt.cosmosdb.models.ServiceStatus + :ivar locations: An array that contains all of the locations for the service. + :vartype locations: + list[~azure.mgmt.cosmosdb.models.MaterializedViewsBuilderRegionalServiceResource] + """ + + _validation = { + "creation_time": {"readonly": True}, + "instance_count": {"minimum": 0}, + "service_type": {"required": True}, + "status": {"readonly": True}, + "locations": {"readonly": True}, + } + + _attribute_map = { + "additional_properties": {"key": "", "type": "{object}"}, + "creation_time": {"key": "creationTime", "type": "iso-8601"}, + "instance_size": {"key": "instanceSize", "type": "str"}, + "instance_count": {"key": "instanceCount", "type": "int"}, + "service_type": {"key": "serviceType", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "locations": {"key": "locations", "type": "[MaterializedViewsBuilderRegionalServiceResource]"}, + } + + def __init__( + self, + *, + additional_properties: Optional[Dict[str, Any]] = None, + instance_size: Optional[Union[str, "_models.ServiceSize"]] = None, + instance_count: Optional[int] = None, + **kwargs: Any + ) -> None: + """ + :keyword additional_properties: Unmatched properties from the message are deserialized to this + collection. + :paramtype additional_properties: dict[str, any] + :keyword instance_size: Instance type for the service. Known values are: "Cosmos.D4s", + "Cosmos.D8s", and "Cosmos.D16s". + :paramtype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize + :keyword instance_count: Instance count for the service. + :paramtype instance_count: int + """ + super().__init__( + additional_properties=additional_properties, + instance_size=instance_size, + instance_count=instance_count, + **kwargs + ) + self.service_type: str = "MaterializedViewsBuilder" + self.locations = None + + +class MergeParameters(_serialization.Model): + """The properties of an Azure Cosmos DB merge operations. + + :ivar is_dry_run: Specifies whether the operation is a real merge operation or a simulation. + :vartype is_dry_run: bool + """ + + _attribute_map = { + "is_dry_run": {"key": "isDryRun", "type": "bool"}, + } + + def __init__(self, *, is_dry_run: Optional[bool] = None, **kwargs: Any) -> None: + """ + :keyword is_dry_run: Specifies whether the operation is a real merge operation or a simulation. + :paramtype is_dry_run: bool + """ + super().__init__(**kwargs) + self.is_dry_run = is_dry_run + + +class Metric(_serialization.Model): + """Metric data. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar start_time: The start time for the metric (ISO-8601 format). + :vartype start_time: ~datetime.datetime + :ivar end_time: The end time for the metric (ISO-8601 format). + :vartype end_time: ~datetime.datetime + :ivar time_grain: The time grain to be used to summarize the metric values. + :vartype time_grain: str + :ivar unit: The unit of the metric. Known values are: "Count", "Bytes", "Seconds", "Percent", + "CountPerSecond", "BytesPerSecond", and "Milliseconds". + :vartype unit: str or ~azure.mgmt.cosmosdb.models.UnitType + :ivar name: The name information for the metric. + :vartype name: ~azure.mgmt.cosmosdb.models.MetricName + :ivar metric_values: The metric values for the specified time window and timestep. + :vartype metric_values: list[~azure.mgmt.cosmosdb.models.MetricValue] + """ + + _validation = { + "start_time": {"readonly": True}, + "end_time": {"readonly": True}, + "time_grain": {"readonly": True}, + "unit": {"readonly": True}, + "name": {"readonly": True}, + "metric_values": {"readonly": True}, + } + + _attribute_map = { + "start_time": {"key": "startTime", "type": "iso-8601"}, + "end_time": {"key": "endTime", "type": "iso-8601"}, + "time_grain": {"key": "timeGrain", "type": "str"}, + "unit": {"key": "unit", "type": "str"}, + "name": {"key": "name", "type": "MetricName"}, + "metric_values": {"key": "metricValues", "type": "[MetricValue]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.start_time = None + self.end_time = None + self.time_grain = None + self.unit = None + self.name = None + self.metric_values = None + + +class MetricAvailability(_serialization.Model): + """The availability of the metric. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar time_grain: The time grain to be used to summarize the metric values. + :vartype time_grain: str + :ivar retention: The retention for the metric values. + :vartype retention: str + """ + + _validation = { + "time_grain": {"readonly": True}, + "retention": {"readonly": True}, + } + + _attribute_map = { + "time_grain": {"key": "timeGrain", "type": "str"}, + "retention": {"key": "retention", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.time_grain = None + self.retention = None + + +class MetricDefinition(_serialization.Model): + """The definition of a metric. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar metric_availabilities: The list of metric availabilities for the account. + :vartype metric_availabilities: list[~azure.mgmt.cosmosdb.models.MetricAvailability] + :ivar primary_aggregation_type: The primary aggregation type of the metric. Known values are: + "None", "Average", "Total", "Minimum", "Maximum", and "Last". + :vartype primary_aggregation_type: str or ~azure.mgmt.cosmosdb.models.PrimaryAggregationType + :ivar unit: The unit of the metric. Known values are: "Count", "Bytes", "Seconds", "Percent", + "CountPerSecond", "BytesPerSecond", and "Milliseconds". + :vartype unit: str or ~azure.mgmt.cosmosdb.models.UnitType + :ivar resource_uri: The resource uri of the database. + :vartype resource_uri: str + :ivar name: The name information for the metric. + :vartype name: ~azure.mgmt.cosmosdb.models.MetricName + """ + + _validation = { + "metric_availabilities": {"readonly": True}, + "primary_aggregation_type": {"readonly": True}, + "unit": {"readonly": True}, + "resource_uri": {"readonly": True}, + "name": {"readonly": True}, + } + + _attribute_map = { + "metric_availabilities": {"key": "metricAvailabilities", "type": "[MetricAvailability]"}, + "primary_aggregation_type": {"key": "primaryAggregationType", "type": "str"}, + "unit": {"key": "unit", "type": "str"}, + "resource_uri": {"key": "resourceUri", "type": "str"}, + "name": {"key": "name", "type": "MetricName"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.metric_availabilities = None + self.primary_aggregation_type = None + self.unit = None + self.resource_uri = None + self.name = None + + +class MetricDefinitionsListResult(_serialization.Model): + """The response to a list metric definitions request. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: The list of metric definitions for the account. + :vartype value: list[~azure.mgmt.cosmosdb.models.MetricDefinition] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[MetricDefinition]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class MetricListResult(_serialization.Model): + """The response to a list metrics request. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: The list of metrics for the account. + :vartype value: list[~azure.mgmt.cosmosdb.models.Metric] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[Metric]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class MetricName(_serialization.Model): + """A metric name. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: The name of the metric. + :vartype value: str + :ivar localized_value: The friendly name of the metric. + :vartype localized_value: str + """ + + _validation = { + "value": {"readonly": True}, + "localized_value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "str"}, + "localized_value": {"key": "localizedValue", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + self.localized_value = None + + +class MetricValue(_serialization.Model): + """Represents metrics values. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar count: The number of values for the metric. + :vartype count: int + :ivar average: The average value of the metric. + :vartype average: float + :ivar maximum: The max value of the metric. + :vartype maximum: float + :ivar minimum: The min value of the metric. + :vartype minimum: float + :ivar timestamp: The metric timestamp (ISO-8601 format). + :vartype timestamp: ~datetime.datetime + :ivar total: The total value of the metric. + :vartype total: float + """ + + _validation = { + "count": {"readonly": True}, + "average": {"readonly": True}, + "maximum": {"readonly": True}, + "minimum": {"readonly": True}, + "timestamp": {"readonly": True}, + "total": {"readonly": True}, + } + + _attribute_map = { + "count": {"key": "_count", "type": "int"}, + "average": {"key": "average", "type": "float"}, + "maximum": {"key": "maximum", "type": "float"}, + "minimum": {"key": "minimum", "type": "float"}, + "timestamp": {"key": "timestamp", "type": "iso-8601"}, + "total": {"key": "total", "type": "float"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.count = None + self.average = None + self.maximum = None + self.minimum = None + self.timestamp = None + self.total = None + + +class MongoDBCollectionCreateUpdateParameters(ARMResourceProperties): + """Parameters to create and update Cosmos DB MongoDB collection. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: The standard JSON format of a MongoDB collection. Required. + :vartype resource: ~azure.mgmt.cosmosdb.models.MongoDBCollectionResource + :ivar options: A key-value pair of options to be applied for the request. This corresponds to + the headers sent with the request. + :vartype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "resource": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "MongoDBCollectionResource"}, + "options": {"key": "properties.options", "type": "CreateUpdateOptions"}, + } + + def __init__( + self, + *, + resource: "_models.MongoDBCollectionResource", + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + options: Optional["_models.CreateUpdateOptions"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: The standard JSON format of a MongoDB collection. Required. + :paramtype resource: ~azure.mgmt.cosmosdb.models.MongoDBCollectionResource + :keyword options: A key-value pair of options to be applied for the request. This corresponds + to the headers sent with the request. + :paramtype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + self.options = options + + +class MongoDBCollectionGetPropertiesOptions(OptionsResource): + """MongoDBCollectionGetPropertiesOptions. + + :ivar throughput: Value of the Cosmos DB resource throughput or autoscaleSettings. Use the + ThroughputSetting resource when retrieving offer details. + :vartype throughput: int + :ivar autoscale_settings: Specifies the Autoscale settings. + :vartype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettings + """ + + +class MongoDBCollectionResource(_serialization.Model): + """Cosmos DB MongoDB collection resource object. + + All required parameters must be populated in order to send to server. + + :ivar id: Name of the Cosmos DB MongoDB collection. Required. + :vartype id: str + :ivar shard_key: A key-value pair of shard keys to be applied for the request. + :vartype shard_key: dict[str, str] + :ivar indexes: List of index keys. + :vartype indexes: list[~azure.mgmt.cosmosdb.models.MongoIndex] + :ivar analytical_storage_ttl: Analytical TTL. + :vartype analytical_storage_ttl: int + :ivar restore_parameters: Parameters to indicate the information about the restore. + :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" + and "Restore". + :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + """ + + _validation = { + "id": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "shard_key": {"key": "shardKey", "type": "{str}"}, + "indexes": {"key": "indexes", "type": "[MongoIndex]"}, + "analytical_storage_ttl": {"key": "analyticalStorageTtl", "type": "int"}, + "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, + "create_mode": {"key": "createMode", "type": "str"}, + } + + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + shard_key: Optional[Dict[str, str]] = None, + indexes: Optional[List["_models.MongoIndex"]] = None, + analytical_storage_ttl: Optional[int] = None, + restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, + create_mode: Union[str, "_models.CreateMode"] = "Default", + **kwargs: Any + ) -> None: + """ + :keyword id: Name of the Cosmos DB MongoDB collection. Required. + :paramtype id: str + :keyword shard_key: A key-value pair of shard keys to be applied for the request. + :paramtype shard_key: dict[str, str] + :keyword indexes: List of index keys. + :paramtype indexes: list[~azure.mgmt.cosmosdb.models.MongoIndex] + :keyword analytical_storage_ttl: Analytical TTL. + :paramtype analytical_storage_ttl: int + :keyword restore_parameters: Parameters to indicate the information about the restore. + :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: + "Default" and "Restore". + :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + """ + super().__init__(**kwargs) + self.id = id + self.shard_key = shard_key + self.indexes = indexes + self.analytical_storage_ttl = analytical_storage_ttl + self.restore_parameters = restore_parameters + self.create_mode = create_mode + + +class MongoDBCollectionGetPropertiesResource(MongoDBCollectionResource, ExtendedResourceProperties): + """MongoDBCollectionGetPropertiesResource. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar rid: A system generated property. A unique identifier. + :vartype rid: str + :ivar ts: A system generated property that denotes the last updated timestamp of the resource. + :vartype ts: float + :ivar etag: A system generated property representing the resource etag required for optimistic + concurrency control. + :vartype etag: str + :ivar id: Name of the Cosmos DB MongoDB collection. Required. + :vartype id: str + :ivar shard_key: A key-value pair of shard keys to be applied for the request. + :vartype shard_key: dict[str, str] + :ivar indexes: List of index keys. + :vartype indexes: list[~azure.mgmt.cosmosdb.models.MongoIndex] + :ivar analytical_storage_ttl: Analytical TTL. + :vartype analytical_storage_ttl: int + :ivar restore_parameters: Parameters to indicate the information about the restore. + :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" + and "Restore". + :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + """ + + _validation = { + "rid": {"readonly": True}, + "ts": {"readonly": True}, + "etag": {"readonly": True}, + "id": {"required": True}, + } + + _attribute_map = { + "rid": {"key": "_rid", "type": "str"}, + "ts": {"key": "_ts", "type": "float"}, + "etag": {"key": "_etag", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "shard_key": {"key": "shardKey", "type": "{str}"}, + "indexes": {"key": "indexes", "type": "[MongoIndex]"}, + "analytical_storage_ttl": {"key": "analyticalStorageTtl", "type": "int"}, + "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, + "create_mode": {"key": "createMode", "type": "str"}, + } + + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + shard_key: Optional[Dict[str, str]] = None, + indexes: Optional[List["_models.MongoIndex"]] = None, + analytical_storage_ttl: Optional[int] = None, + restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, + create_mode: Union[str, "_models.CreateMode"] = "Default", + **kwargs: Any + ) -> None: + """ + :keyword id: Name of the Cosmos DB MongoDB collection. Required. + :paramtype id: str + :keyword shard_key: A key-value pair of shard keys to be applied for the request. + :paramtype shard_key: dict[str, str] + :keyword indexes: List of index keys. + :paramtype indexes: list[~azure.mgmt.cosmosdb.models.MongoIndex] + :keyword analytical_storage_ttl: Analytical TTL. + :paramtype analytical_storage_ttl: int + :keyword restore_parameters: Parameters to indicate the information about the restore. + :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: + "Default" and "Restore". + :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + """ + super().__init__( + id=id, + shard_key=shard_key, + indexes=indexes, + analytical_storage_ttl=analytical_storage_ttl, + restore_parameters=restore_parameters, + create_mode=create_mode, + **kwargs + ) + self.rid = None + self.ts = None + self.etag = None + self.id = id + self.shard_key = shard_key + self.indexes = indexes + self.analytical_storage_ttl = analytical_storage_ttl + self.restore_parameters = restore_parameters + self.create_mode = create_mode + + +class MongoDBCollectionGetResults(ARMResourceProperties): + """An Azure Cosmos DB MongoDB collection. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: + :vartype resource: ~azure.mgmt.cosmosdb.models.MongoDBCollectionGetPropertiesResource + :ivar options: + :vartype options: ~azure.mgmt.cosmosdb.models.MongoDBCollectionGetPropertiesOptions + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "MongoDBCollectionGetPropertiesResource"}, + "options": {"key": "properties.options", "type": "MongoDBCollectionGetPropertiesOptions"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + resource: Optional["_models.MongoDBCollectionGetPropertiesResource"] = None, + options: Optional["_models.MongoDBCollectionGetPropertiesOptions"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: + :paramtype resource: ~azure.mgmt.cosmosdb.models.MongoDBCollectionGetPropertiesResource + :keyword options: + :paramtype options: ~azure.mgmt.cosmosdb.models.MongoDBCollectionGetPropertiesOptions + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + self.options = options + + +class MongoDBCollectionListResult(_serialization.Model): + """The List operation response, that contains the MongoDB collections and their properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of MongoDB collections and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.MongoDBCollectionGetResults] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[MongoDBCollectionGetResults]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class MongoDBDatabaseCreateUpdateParameters(ARMResourceProperties): + """Parameters to create and update Cosmos DB MongoDB database. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: The standard JSON format of a MongoDB database. Required. + :vartype resource: ~azure.mgmt.cosmosdb.models.MongoDBDatabaseResource + :ivar options: A key-value pair of options to be applied for the request. This corresponds to + the headers sent with the request. + :vartype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "resource": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "MongoDBDatabaseResource"}, + "options": {"key": "properties.options", "type": "CreateUpdateOptions"}, + } + + def __init__( + self, + *, + resource: "_models.MongoDBDatabaseResource", + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + options: Optional["_models.CreateUpdateOptions"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: The standard JSON format of a MongoDB database. Required. + :paramtype resource: ~azure.mgmt.cosmosdb.models.MongoDBDatabaseResource + :keyword options: A key-value pair of options to be applied for the request. This corresponds + to the headers sent with the request. + :paramtype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + self.options = options + + +class MongoDBDatabaseGetPropertiesOptions(OptionsResource): + """MongoDBDatabaseGetPropertiesOptions. + + :ivar throughput: Value of the Cosmos DB resource throughput or autoscaleSettings. Use the + ThroughputSetting resource when retrieving offer details. + :vartype throughput: int + :ivar autoscale_settings: Specifies the Autoscale settings. + :vartype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettings + """ + + +class MongoDBDatabaseResource(_serialization.Model): + """Cosmos DB MongoDB database resource object. + + All required parameters must be populated in order to send to server. + + :ivar id: Name of the Cosmos DB MongoDB database. Required. + :vartype id: str + :ivar restore_parameters: Parameters to indicate the information about the restore. + :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" + and "Restore". + :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + """ + + _validation = { + "id": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, + "create_mode": {"key": "createMode", "type": "str"}, + } + + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, + create_mode: Union[str, "_models.CreateMode"] = "Default", + **kwargs: Any + ) -> None: + """ + :keyword id: Name of the Cosmos DB MongoDB database. Required. + :paramtype id: str + :keyword restore_parameters: Parameters to indicate the information about the restore. + :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: + "Default" and "Restore". + :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + """ + super().__init__(**kwargs) + self.id = id + self.restore_parameters = restore_parameters + self.create_mode = create_mode + + +class MongoDBDatabaseGetPropertiesResource(MongoDBDatabaseResource, ExtendedResourceProperties): + """MongoDBDatabaseGetPropertiesResource. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar rid: A system generated property. A unique identifier. + :vartype rid: str + :ivar ts: A system generated property that denotes the last updated timestamp of the resource. + :vartype ts: float + :ivar etag: A system generated property representing the resource etag required for optimistic + concurrency control. + :vartype etag: str + :ivar id: Name of the Cosmos DB MongoDB database. Required. + :vartype id: str + :ivar restore_parameters: Parameters to indicate the information about the restore. + :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" + and "Restore". + :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + """ + + _validation = { + "rid": {"readonly": True}, + "ts": {"readonly": True}, + "etag": {"readonly": True}, + "id": {"required": True}, + } + + _attribute_map = { + "rid": {"key": "_rid", "type": "str"}, + "ts": {"key": "_ts", "type": "float"}, + "etag": {"key": "_etag", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, + "create_mode": {"key": "createMode", "type": "str"}, + } + + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, + create_mode: Union[str, "_models.CreateMode"] = "Default", + **kwargs: Any + ) -> None: + """ + :keyword id: Name of the Cosmos DB MongoDB database. Required. + :paramtype id: str + :keyword restore_parameters: Parameters to indicate the information about the restore. + :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: + "Default" and "Restore". + :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + """ + super().__init__(id=id, restore_parameters=restore_parameters, create_mode=create_mode, **kwargs) + self.rid = None + self.ts = None + self.etag = None + self.id = id + self.restore_parameters = restore_parameters + self.create_mode = create_mode + + +class MongoDBDatabaseGetResults(ARMResourceProperties): + """An Azure Cosmos DB MongoDB database. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: + :vartype resource: ~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetPropertiesResource + :ivar options: + :vartype options: ~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetPropertiesOptions + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "MongoDBDatabaseGetPropertiesResource"}, + "options": {"key": "properties.options", "type": "MongoDBDatabaseGetPropertiesOptions"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + resource: Optional["_models.MongoDBDatabaseGetPropertiesResource"] = None, + options: Optional["_models.MongoDBDatabaseGetPropertiesOptions"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: + :paramtype resource: ~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetPropertiesResource + :keyword options: + :paramtype options: ~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetPropertiesOptions + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + self.options = options + + +class MongoDBDatabaseListResult(_serialization.Model): + """The List operation response, that contains the MongoDB databases and their properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of MongoDB databases and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetResults] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[MongoDBDatabaseGetResults]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class MongoIndex(_serialization.Model): + """Cosmos DB MongoDB collection index key. + + :ivar key: Cosmos DB MongoDB collection index keys. + :vartype key: ~azure.mgmt.cosmosdb.models.MongoIndexKeys + :ivar options: Cosmos DB MongoDB collection index key options. + :vartype options: ~azure.mgmt.cosmosdb.models.MongoIndexOptions + """ + + _attribute_map = { + "key": {"key": "key", "type": "MongoIndexKeys"}, + "options": {"key": "options", "type": "MongoIndexOptions"}, + } + + def __init__( + self, + *, + key: Optional["_models.MongoIndexKeys"] = None, + options: Optional["_models.MongoIndexOptions"] = None, + **kwargs: Any + ) -> None: + """ + :keyword key: Cosmos DB MongoDB collection index keys. + :paramtype key: ~azure.mgmt.cosmosdb.models.MongoIndexKeys + :keyword options: Cosmos DB MongoDB collection index key options. + :paramtype options: ~azure.mgmt.cosmosdb.models.MongoIndexOptions + """ + super().__init__(**kwargs) + self.key = key + self.options = options + + +class MongoIndexKeys(_serialization.Model): + """Cosmos DB MongoDB collection resource object. + + :ivar keys: List of keys for each MongoDB collection in the Azure Cosmos DB service. + :vartype keys: list[str] + """ + + _attribute_map = { + "keys": {"key": "keys", "type": "[str]"}, + } + + def __init__(self, *, keys: Optional[List[str]] = None, **kwargs: Any) -> None: + """ + :keyword keys: List of keys for each MongoDB collection in the Azure Cosmos DB service. + :paramtype keys: list[str] + """ + super().__init__(**kwargs) + self.keys = keys + + +class MongoIndexOptions(_serialization.Model): + """Cosmos DB MongoDB collection index options. + + :ivar expire_after_seconds: Expire after seconds. + :vartype expire_after_seconds: int + :ivar unique: Is unique or not. + :vartype unique: bool + """ + + _attribute_map = { + "expire_after_seconds": {"key": "expireAfterSeconds", "type": "int"}, + "unique": {"key": "unique", "type": "bool"}, + } + + def __init__( + self, *, expire_after_seconds: Optional[int] = None, unique: Optional[bool] = None, **kwargs: Any + ) -> None: + """ + :keyword expire_after_seconds: Expire after seconds. + :paramtype expire_after_seconds: int + :keyword unique: Is unique or not. + :paramtype unique: bool + """ + super().__init__(**kwargs) + self.expire_after_seconds = expire_after_seconds + self.unique = unique + + +class MongoRoleDefinitionCreateUpdateParameters(_serialization.Model): # pylint: disable=name-too-long + """Parameters to create and update an Azure Cosmos DB Mongo Role Definition. + + :ivar role_name: A user-friendly name for the Role Definition. Must be unique for the database + account. + :vartype role_name: str + :ivar type: Indicates whether the Role Definition was built-in or user created. Known values + are: "BuiltInRole" and "CustomRole". + :vartype type: str or ~azure.mgmt.cosmosdb.models.MongoRoleDefinitionType + :ivar database_name: The database name for which access is being granted for this Role + Definition. + :vartype database_name: str + :ivar privileges: A set of privileges contained by the Role Definition. This will allow + application of this Role Definition on the entire database account or any underlying Database / + Collection. Scopes higher than Database are not enforceable as privilege. + :vartype privileges: list[~azure.mgmt.cosmosdb.models.Privilege] + :ivar roles: The set of roles inherited by this Role Definition. + :vartype roles: list[~azure.mgmt.cosmosdb.models.Role] + """ + + _attribute_map = { + "role_name": {"key": "properties.roleName", "type": "str"}, + "type": {"key": "properties.type", "type": "str"}, + "database_name": {"key": "properties.databaseName", "type": "str"}, + "privileges": {"key": "properties.privileges", "type": "[Privilege]"}, + "roles": {"key": "properties.roles", "type": "[Role]"}, + } + + def __init__( + self, + *, + role_name: Optional[str] = None, + type: Optional[Union[str, "_models.MongoRoleDefinitionType"]] = None, + database_name: Optional[str] = None, + privileges: Optional[List["_models.Privilege"]] = None, + roles: Optional[List["_models.Role"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword role_name: A user-friendly name for the Role Definition. Must be unique for the + database account. + :paramtype role_name: str + :keyword type: Indicates whether the Role Definition was built-in or user created. Known values + are: "BuiltInRole" and "CustomRole". + :paramtype type: str or ~azure.mgmt.cosmosdb.models.MongoRoleDefinitionType + :keyword database_name: The database name for which access is being granted for this Role + Definition. + :paramtype database_name: str + :keyword privileges: A set of privileges contained by the Role Definition. This will allow + application of this Role Definition on the entire database account or any underlying Database / + Collection. Scopes higher than Database are not enforceable as privilege. + :paramtype privileges: list[~azure.mgmt.cosmosdb.models.Privilege] + :keyword roles: The set of roles inherited by this Role Definition. + :paramtype roles: list[~azure.mgmt.cosmosdb.models.Role] + """ + super().__init__(**kwargs) + self.role_name = role_name + self.type = type + self.database_name = database_name + self.privileges = privileges + self.roles = roles + + +class MongoRoleDefinitionGetResults(ARMProxyResource): + """An Azure Cosmos DB Mongo Role Definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the database account. + :vartype id: str + :ivar name: The name of the database account. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar role_name: A user-friendly name for the Role Definition. Must be unique for the database + account. + :vartype role_name: str + :ivar type_properties_type: Indicates whether the Role Definition was built-in or user created. + Known values are: "BuiltInRole" and "CustomRole". + :vartype type_properties_type: str or ~azure.mgmt.cosmosdb.models.MongoRoleDefinitionType + :ivar database_name: The database name for which access is being granted for this Role + Definition. + :vartype database_name: str + :ivar privileges: A set of privileges contained by the Role Definition. This will allow + application of this Role Definition on the entire database account or any underlying Database / + Collection. Scopes higher than Database are not enforceable as privilege. + :vartype privileges: list[~azure.mgmt.cosmosdb.models.Privilege] + :ivar roles: The set of roles inherited by this Role Definition. + :vartype roles: list[~azure.mgmt.cosmosdb.models.Role] + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "role_name": {"key": "properties.roleName", "type": "str"}, + "type_properties_type": {"key": "properties.type", "type": "str"}, + "database_name": {"key": "properties.databaseName", "type": "str"}, + "privileges": {"key": "properties.privileges", "type": "[Privilege]"}, + "roles": {"key": "properties.roles", "type": "[Role]"}, + } + + def __init__( + self, + *, + role_name: Optional[str] = None, + type_properties_type: Optional[Union[str, "_models.MongoRoleDefinitionType"]] = None, + database_name: Optional[str] = None, + privileges: Optional[List["_models.Privilege"]] = None, + roles: Optional[List["_models.Role"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword role_name: A user-friendly name for the Role Definition. Must be unique for the + database account. + :paramtype role_name: str + :keyword type_properties_type: Indicates whether the Role Definition was built-in or user + created. Known values are: "BuiltInRole" and "CustomRole". + :paramtype type_properties_type: str or ~azure.mgmt.cosmosdb.models.MongoRoleDefinitionType + :keyword database_name: The database name for which access is being granted for this Role + Definition. + :paramtype database_name: str + :keyword privileges: A set of privileges contained by the Role Definition. This will allow + application of this Role Definition on the entire database account or any underlying Database / + Collection. Scopes higher than Database are not enforceable as privilege. + :paramtype privileges: list[~azure.mgmt.cosmosdb.models.Privilege] + :keyword roles: The set of roles inherited by this Role Definition. + :paramtype roles: list[~azure.mgmt.cosmosdb.models.Role] + """ + super().__init__(**kwargs) + self.role_name = role_name + self.type_properties_type = type_properties_type + self.database_name = database_name + self.privileges = privileges + self.roles = roles + + +class MongoRoleDefinitionListResult(_serialization.Model): + """The relevant Mongo Role Definitions. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of Mongo Role Definitions and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.MongoRoleDefinitionGetResults] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[MongoRoleDefinitionGetResults]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class MongoUserDefinitionCreateUpdateParameters(_serialization.Model): # pylint: disable=name-too-long + """Parameters to create and update an Azure Cosmos DB Mongo User Definition. + + :ivar user_name: The user name for User Definition. + :vartype user_name: str + :ivar password: The password for User Definition. Response does not contain user password. + :vartype password: str + :ivar database_name: The database name for which access is being granted for this User + Definition. + :vartype database_name: str + :ivar custom_data: A custom definition for the USer Definition. + :vartype custom_data: str + :ivar roles: The set of roles inherited by the User Definition. + :vartype roles: list[~azure.mgmt.cosmosdb.models.Role] + :ivar mechanisms: The Mongo Auth mechanism. For now, we only support auth mechanism + SCRAM-SHA-256. + :vartype mechanisms: str + """ + + _attribute_map = { + "user_name": {"key": "properties.userName", "type": "str"}, + "password": {"key": "properties.password", "type": "str"}, + "database_name": {"key": "properties.databaseName", "type": "str"}, + "custom_data": {"key": "properties.customData", "type": "str"}, + "roles": {"key": "properties.roles", "type": "[Role]"}, + "mechanisms": {"key": "properties.mechanisms", "type": "str"}, + } + + def __init__( + self, + *, + user_name: Optional[str] = None, + password: Optional[str] = None, + database_name: Optional[str] = None, + custom_data: Optional[str] = None, + roles: Optional[List["_models.Role"]] = None, + mechanisms: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword user_name: The user name for User Definition. + :paramtype user_name: str + :keyword password: The password for User Definition. Response does not contain user password. + :paramtype password: str + :keyword database_name: The database name for which access is being granted for this User + Definition. + :paramtype database_name: str + :keyword custom_data: A custom definition for the USer Definition. + :paramtype custom_data: str + :keyword roles: The set of roles inherited by the User Definition. + :paramtype roles: list[~azure.mgmt.cosmosdb.models.Role] + :keyword mechanisms: The Mongo Auth mechanism. For now, we only support auth mechanism + SCRAM-SHA-256. + :paramtype mechanisms: str + """ + super().__init__(**kwargs) + self.user_name = user_name + self.password = password + self.database_name = database_name + self.custom_data = custom_data + self.roles = roles + self.mechanisms = mechanisms + + +class MongoUserDefinitionGetResults(ARMProxyResource): + """An Azure Cosmos DB User Definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the database account. + :vartype id: str + :ivar name: The name of the database account. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar user_name: The user name for User Definition. + :vartype user_name: str + :ivar password: The password for User Definition. Response does not contain user password. + :vartype password: str + :ivar database_name: The database name for which access is being granted for this User + Definition. + :vartype database_name: str + :ivar custom_data: A custom definition for the USer Definition. + :vartype custom_data: str + :ivar roles: The set of roles inherited by the User Definition. + :vartype roles: list[~azure.mgmt.cosmosdb.models.Role] + :ivar mechanisms: The Mongo Auth mechanism. For now, we only support auth mechanism + SCRAM-SHA-256. + :vartype mechanisms: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "user_name": {"key": "properties.userName", "type": "str"}, + "password": {"key": "properties.password", "type": "str"}, + "database_name": {"key": "properties.databaseName", "type": "str"}, + "custom_data": {"key": "properties.customData", "type": "str"}, + "roles": {"key": "properties.roles", "type": "[Role]"}, + "mechanisms": {"key": "properties.mechanisms", "type": "str"}, + } + + def __init__( + self, + *, + user_name: Optional[str] = None, + password: Optional[str] = None, + database_name: Optional[str] = None, + custom_data: Optional[str] = None, + roles: Optional[List["_models.Role"]] = None, + mechanisms: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword user_name: The user name for User Definition. + :paramtype user_name: str + :keyword password: The password for User Definition. Response does not contain user password. + :paramtype password: str + :keyword database_name: The database name for which access is being granted for this User + Definition. + :paramtype database_name: str + :keyword custom_data: A custom definition for the USer Definition. + :paramtype custom_data: str + :keyword roles: The set of roles inherited by the User Definition. + :paramtype roles: list[~azure.mgmt.cosmosdb.models.Role] + :keyword mechanisms: The Mongo Auth mechanism. For now, we only support auth mechanism + SCRAM-SHA-256. + :paramtype mechanisms: str + """ + super().__init__(**kwargs) + self.user_name = user_name + self.password = password + self.database_name = database_name + self.custom_data = custom_data + self.roles = roles + self.mechanisms = mechanisms + + +class MongoUserDefinitionListResult(_serialization.Model): + """The relevant User Definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of User Definition and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.MongoUserDefinitionGetResults] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[MongoUserDefinitionGetResults]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class NetworkSecurityPerimeter(_serialization.Model): + """Information about a network security perimeter (NSP). + + :ivar id: Fully qualified Azure resource ID of the NSP resource. + :vartype id: str + :ivar perimeter_guid: Universal unique ID (UUID) of the network security perimeter. + :vartype perimeter_guid: str + :ivar location: Location of the network security perimeter. + :vartype location: str + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "perimeter_guid": {"key": "perimeterGuid", "type": "str"}, + "location": {"key": "location", "type": "str"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + perimeter_guid: Optional[str] = None, + location: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword id: Fully qualified Azure resource ID of the NSP resource. + :paramtype id: str + :keyword perimeter_guid: Universal unique ID (UUID) of the network security perimeter. + :paramtype perimeter_guid: str + :keyword location: Location of the network security perimeter. + :paramtype location: str + """ + super().__init__(**kwargs) + self.id = id + self.perimeter_guid = perimeter_guid + self.location = location + + +class NetworkSecurityPerimeterConfiguration(ProxyResource): + """Network security perimeter (NSP) configuration resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.cosmosdb.models.SystemData + :ivar properties: Network security configuration properties. + :vartype properties: + ~azure.mgmt.cosmosdb.models.NetworkSecurityPerimeterConfigurationProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "properties": {"key": "properties", "type": "NetworkSecurityPerimeterConfigurationProperties"}, + } + + def __init__( + self, *, properties: Optional["_models.NetworkSecurityPerimeterConfigurationProperties"] = None, **kwargs: Any + ) -> None: + """ + :keyword properties: Network security configuration properties. + :paramtype properties: + ~azure.mgmt.cosmosdb.models.NetworkSecurityPerimeterConfigurationProperties + """ + super().__init__(**kwargs) + self.properties = properties + + +class NetworkSecurityPerimeterConfigurationListResult(_serialization.Model): # pylint: disable=name-too-long + """Result of a list NSP (network security perimeter) configurations request. + + :ivar value: Array of network security perimeter results. + :vartype value: list[~azure.mgmt.cosmosdb.models.NetworkSecurityPerimeterConfiguration] + :ivar next_link: The link used to get the next page of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[NetworkSecurityPerimeterConfiguration]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[List["_models.NetworkSecurityPerimeterConfiguration"]] = None, + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword value: Array of network security perimeter results. + :paramtype value: list[~azure.mgmt.cosmosdb.models.NetworkSecurityPerimeterConfiguration] + :keyword next_link: The link used to get the next page of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class NetworkSecurityPerimeterConfigurationProperties(_serialization.Model): # pylint: disable=name-too-long + """Network security configuration properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar provisioning_state: Provisioning state of a network security perimeter configuration that + is being created or updated. Known values are: "Succeeded", "Creating", "Updating", "Deleting", + "Accepted", "Failed", and "Canceled". + :vartype provisioning_state: str or + ~azure.mgmt.cosmosdb.models.NetworkSecurityPerimeterConfigurationProvisioningState + :ivar provisioning_issues: List of provisioning issues, if any. + :vartype provisioning_issues: list[~azure.mgmt.cosmosdb.models.ProvisioningIssue] + :ivar network_security_perimeter: Information about a network security perimeter (NSP). + :vartype network_security_perimeter: ~azure.mgmt.cosmosdb.models.NetworkSecurityPerimeter + :ivar resource_association: Information about resource association. + :vartype resource_association: ~azure.mgmt.cosmosdb.models.ResourceAssociation + :ivar profile: Network security perimeter configuration profile. + :vartype profile: ~azure.mgmt.cosmosdb.models.NetworkSecurityProfile + """ + + _validation = { + "provisioning_state": {"readonly": True}, + "provisioning_issues": {"readonly": True}, + } + + _attribute_map = { + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "provisioning_issues": {"key": "provisioningIssues", "type": "[ProvisioningIssue]"}, + "network_security_perimeter": {"key": "networkSecurityPerimeter", "type": "NetworkSecurityPerimeter"}, + "resource_association": {"key": "resourceAssociation", "type": "ResourceAssociation"}, + "profile": {"key": "profile", "type": "NetworkSecurityProfile"}, + } + + def __init__( + self, + *, + network_security_perimeter: Optional["_models.NetworkSecurityPerimeter"] = None, + resource_association: Optional["_models.ResourceAssociation"] = None, + profile: Optional["_models.NetworkSecurityProfile"] = None, + **kwargs: Any + ) -> None: + """ + :keyword network_security_perimeter: Information about a network security perimeter (NSP). + :paramtype network_security_perimeter: ~azure.mgmt.cosmosdb.models.NetworkSecurityPerimeter + :keyword resource_association: Information about resource association. + :paramtype resource_association: ~azure.mgmt.cosmosdb.models.ResourceAssociation + :keyword profile: Network security perimeter configuration profile. + :paramtype profile: ~azure.mgmt.cosmosdb.models.NetworkSecurityProfile + """ + super().__init__(**kwargs) + self.provisioning_state = None + self.provisioning_issues = None + self.network_security_perimeter = network_security_perimeter + self.resource_association = resource_association + self.profile = profile + + +class NetworkSecurityProfile(_serialization.Model): + """Network security perimeter configuration profile. + + :ivar name: Name of the profile. + :vartype name: str + :ivar access_rules_version: Current access rules version. + :vartype access_rules_version: int + :ivar access_rules: List of Access Rules. + :vartype access_rules: list[~azure.mgmt.cosmosdb.models.AccessRule] + :ivar diagnostic_settings_version: Current diagnostic settings version. + :vartype diagnostic_settings_version: int + :ivar enabled_log_categories: List of log categories that are enabled. + :vartype enabled_log_categories: list[str] + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "access_rules_version": {"key": "accessRulesVersion", "type": "int"}, + "access_rules": {"key": "accessRules", "type": "[AccessRule]"}, + "diagnostic_settings_version": {"key": "diagnosticSettingsVersion", "type": "int"}, + "enabled_log_categories": {"key": "enabledLogCategories", "type": "[str]"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + access_rules_version: Optional[int] = None, + access_rules: Optional[List["_models.AccessRule"]] = None, + diagnostic_settings_version: Optional[int] = None, + enabled_log_categories: Optional[List[str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: Name of the profile. + :paramtype name: str + :keyword access_rules_version: Current access rules version. + :paramtype access_rules_version: int + :keyword access_rules: List of Access Rules. + :paramtype access_rules: list[~azure.mgmt.cosmosdb.models.AccessRule] + :keyword diagnostic_settings_version: Current diagnostic settings version. + :paramtype diagnostic_settings_version: int + :keyword enabled_log_categories: List of log categories that are enabled. + :paramtype enabled_log_categories: list[str] + """ + super().__init__(**kwargs) + self.name = name + self.access_rules_version = access_rules_version + self.access_rules = access_rules + self.diagnostic_settings_version = diagnostic_settings_version + self.enabled_log_categories = enabled_log_categories + + +class NotebookWorkspace(ARMProxyResource): + """A notebook workspace resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the database account. + :vartype id: str + :ivar name: The name of the database account. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar notebook_server_endpoint: Specifies the endpoint of Notebook server. + :vartype notebook_server_endpoint: str + :ivar status: Status of the notebook workspace. Possible values are: Creating, Online, + Deleting, Failed, Updating. + :vartype status: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "notebook_server_endpoint": {"readonly": True}, + "status": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "notebook_server_endpoint": {"key": "properties.notebookServerEndpoint", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.notebook_server_endpoint = None + self.status = None + + +class NotebookWorkspaceConnectionInfoResult(_serialization.Model): + """The connection info for the given notebook workspace. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar auth_token: Specifies auth token used for connecting to Notebook server (uses token-based + auth). + :vartype auth_token: str + :ivar notebook_server_endpoint: Specifies the endpoint of Notebook server. + :vartype notebook_server_endpoint: str + """ + + _validation = { + "auth_token": {"readonly": True}, + "notebook_server_endpoint": {"readonly": True}, + } + + _attribute_map = { + "auth_token": {"key": "authToken", "type": "str"}, + "notebook_server_endpoint": {"key": "notebookServerEndpoint", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.auth_token = None + self.notebook_server_endpoint = None + + +class NotebookWorkspaceCreateUpdateParameters(ARMProxyResource): + """Parameters to create a notebook workspace resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the database account. + :vartype id: str + :ivar name: The name of the database account. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + """ + + +class NotebookWorkspaceListResult(_serialization.Model): + """A list of notebook workspace resources. + + :ivar value: Array of notebook workspace resources. + :vartype value: list[~azure.mgmt.cosmosdb.models.NotebookWorkspace] + """ + + _attribute_map = { + "value": {"key": "value", "type": "[NotebookWorkspace]"}, + } + + def __init__(self, *, value: Optional[List["_models.NotebookWorkspace"]] = None, **kwargs: Any) -> None: + """ + :keyword value: Array of notebook workspace resources. + :paramtype value: list[~azure.mgmt.cosmosdb.models.NotebookWorkspace] + """ + super().__init__(**kwargs) + self.value = value + + +class Operation(_serialization.Model): + """REST API operation. + + :ivar name: Operation name: {provider}/{resource}/{operation}. + :vartype name: str + :ivar display: The object that represents the operation. + :vartype display: ~azure.mgmt.cosmosdb.models.OperationDisplay + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "display": {"key": "display", "type": "OperationDisplay"}, + } + + def __init__( + self, *, name: Optional[str] = None, display: Optional["_models.OperationDisplay"] = None, **kwargs: Any + ) -> None: + """ + :keyword name: Operation name: {provider}/{resource}/{operation}. + :paramtype name: str + :keyword display: The object that represents the operation. + :paramtype display: ~azure.mgmt.cosmosdb.models.OperationDisplay + """ + super().__init__(**kwargs) + self.name = name + self.display = display + + +class OperationDisplay(_serialization.Model): + """The object that represents the operation. + + :ivar provider: Service provider: Microsoft.ResourceProvider. + :vartype provider: str + :ivar resource: Resource on which the operation is performed: Profile, endpoint, etc. + :vartype resource: str + :ivar operation: Operation type: Read, write, delete, etc. + :vartype operation: str + :ivar description: Description of operation. + :vartype description: str + """ + + _attribute_map = { + "provider": {"key": "Provider", "type": "str"}, + "resource": {"key": "Resource", "type": "str"}, + "operation": {"key": "Operation", "type": "str"}, + "description": {"key": "Description", "type": "str"}, + } + + def __init__( + self, + *, + provider: Optional[str] = None, + resource: Optional[str] = None, + operation: Optional[str] = None, + description: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword provider: Service provider: Microsoft.ResourceProvider. + :paramtype provider: str + :keyword resource: Resource on which the operation is performed: Profile, endpoint, etc. + :paramtype resource: str + :keyword operation: Operation type: Read, write, delete, etc. + :paramtype operation: str + :keyword description: Description of operation. + :paramtype description: str + """ + super().__init__(**kwargs) + self.provider = provider + self.resource = resource + self.operation = operation + self.description = description + + +class OperationListResult(_serialization.Model): + """Result of the request to list Resource Provider operations. It contains a list of operations + and a URL link to get the next set of results. + + :ivar value: List of operations supported by the Resource Provider. + :vartype value: list[~azure.mgmt.cosmosdb.models.Operation] + :ivar next_link: URL to get the next set of operation list results if there are any. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[Operation]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[List["_models.Operation"]] = None, next_link: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword value: List of operations supported by the Resource Provider. + :paramtype value: list[~azure.mgmt.cosmosdb.models.Operation] + :keyword next_link: URL to get the next set of operation list results if there are any. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class PartitionMetric(Metric): + """The metric values for a single partition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar start_time: The start time for the metric (ISO-8601 format). + :vartype start_time: ~datetime.datetime + :ivar end_time: The end time for the metric (ISO-8601 format). + :vartype end_time: ~datetime.datetime + :ivar time_grain: The time grain to be used to summarize the metric values. + :vartype time_grain: str + :ivar unit: The unit of the metric. Known values are: "Count", "Bytes", "Seconds", "Percent", + "CountPerSecond", "BytesPerSecond", and "Milliseconds". + :vartype unit: str or ~azure.mgmt.cosmosdb.models.UnitType + :ivar name: The name information for the metric. + :vartype name: ~azure.mgmt.cosmosdb.models.MetricName + :ivar metric_values: The metric values for the specified time window and timestep. + :vartype metric_values: list[~azure.mgmt.cosmosdb.models.MetricValue] + :ivar partition_id: The partition id (GUID identifier) of the metric values. + :vartype partition_id: str + :ivar partition_key_range_id: The partition key range id (integer identifier) of the metric + values. + :vartype partition_key_range_id: str + """ + + _validation = { + "start_time": {"readonly": True}, + "end_time": {"readonly": True}, + "time_grain": {"readonly": True}, + "unit": {"readonly": True}, + "name": {"readonly": True}, + "metric_values": {"readonly": True}, + "partition_id": {"readonly": True}, + "partition_key_range_id": {"readonly": True}, + } + + _attribute_map = { + "start_time": {"key": "startTime", "type": "iso-8601"}, + "end_time": {"key": "endTime", "type": "iso-8601"}, + "time_grain": {"key": "timeGrain", "type": "str"}, + "unit": {"key": "unit", "type": "str"}, + "name": {"key": "name", "type": "MetricName"}, + "metric_values": {"key": "metricValues", "type": "[MetricValue]"}, + "partition_id": {"key": "partitionId", "type": "str"}, + "partition_key_range_id": {"key": "partitionKeyRangeId", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.partition_id = None + self.partition_key_range_id = None + + +class PartitionMetricListResult(_serialization.Model): + """The response to a list partition metrics request. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: The list of partition-level metrics for the account. + :vartype value: list[~azure.mgmt.cosmosdb.models.PartitionMetric] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[PartitionMetric]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class Usage(_serialization.Model): + """The usage data for a usage request. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar unit: The unit of the metric. Known values are: "Count", "Bytes", "Seconds", "Percent", + "CountPerSecond", "BytesPerSecond", and "Milliseconds". + :vartype unit: str or ~azure.mgmt.cosmosdb.models.UnitType + :ivar name: The name information for the metric. + :vartype name: ~azure.mgmt.cosmosdb.models.MetricName + :ivar quota_period: The quota period used to summarize the usage values. + :vartype quota_period: str + :ivar limit: Maximum value for this metric. + :vartype limit: int + :ivar current_value: Current value for this metric. + :vartype current_value: int + """ + + _validation = { + "unit": {"readonly": True}, + "name": {"readonly": True}, + "quota_period": {"readonly": True}, + "limit": {"readonly": True}, + "current_value": {"readonly": True}, + } + + _attribute_map = { + "unit": {"key": "unit", "type": "str"}, + "name": {"key": "name", "type": "MetricName"}, + "quota_period": {"key": "quotaPeriod", "type": "str"}, + "limit": {"key": "limit", "type": "int"}, + "current_value": {"key": "currentValue", "type": "int"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.unit = None + self.name = None + self.quota_period = None + self.limit = None + self.current_value = None + + +class PartitionUsage(Usage): + """The partition level usage data for a usage request. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar unit: The unit of the metric. Known values are: "Count", "Bytes", "Seconds", "Percent", + "CountPerSecond", "BytesPerSecond", and "Milliseconds". + :vartype unit: str or ~azure.mgmt.cosmosdb.models.UnitType + :ivar name: The name information for the metric. + :vartype name: ~azure.mgmt.cosmosdb.models.MetricName + :ivar quota_period: The quota period used to summarize the usage values. + :vartype quota_period: str + :ivar limit: Maximum value for this metric. + :vartype limit: int + :ivar current_value: Current value for this metric. + :vartype current_value: int + :ivar partition_id: The partition id (GUID identifier) of the usages. + :vartype partition_id: str + :ivar partition_key_range_id: The partition key range id (integer identifier) of the usages. + :vartype partition_key_range_id: str + """ + + _validation = { + "unit": {"readonly": True}, + "name": {"readonly": True}, + "quota_period": {"readonly": True}, + "limit": {"readonly": True}, + "current_value": {"readonly": True}, + "partition_id": {"readonly": True}, + "partition_key_range_id": {"readonly": True}, + } + + _attribute_map = { + "unit": {"key": "unit", "type": "str"}, + "name": {"key": "name", "type": "MetricName"}, + "quota_period": {"key": "quotaPeriod", "type": "str"}, + "limit": {"key": "limit", "type": "int"}, + "current_value": {"key": "currentValue", "type": "int"}, + "partition_id": {"key": "partitionId", "type": "str"}, + "partition_key_range_id": {"key": "partitionKeyRangeId", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.partition_id = None + self.partition_key_range_id = None + + +class PartitionUsagesResult(_serialization.Model): + """The response to a list partition level usage request. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: The list of partition-level usages for the database. A usage is a point in time + metric. + :vartype value: list[~azure.mgmt.cosmosdb.models.PartitionUsage] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[PartitionUsage]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class PercentileMetric(_serialization.Model): + """Percentile Metric data. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar start_time: The start time for the metric (ISO-8601 format). + :vartype start_time: ~datetime.datetime + :ivar end_time: The end time for the metric (ISO-8601 format). + :vartype end_time: ~datetime.datetime + :ivar time_grain: The time grain to be used to summarize the metric values. + :vartype time_grain: str + :ivar unit: The unit of the metric. Known values are: "Count", "Bytes", "Seconds", "Percent", + "CountPerSecond", "BytesPerSecond", and "Milliseconds". + :vartype unit: str or ~azure.mgmt.cosmosdb.models.UnitType + :ivar name: The name information for the metric. + :vartype name: ~azure.mgmt.cosmosdb.models.MetricName + :ivar metric_values: The percentile metric values for the specified time window and timestep. + :vartype metric_values: list[~azure.mgmt.cosmosdb.models.PercentileMetricValue] + """ + + _validation = { + "start_time": {"readonly": True}, + "end_time": {"readonly": True}, + "time_grain": {"readonly": True}, + "unit": {"readonly": True}, + "name": {"readonly": True}, + "metric_values": {"readonly": True}, + } + + _attribute_map = { + "start_time": {"key": "startTime", "type": "iso-8601"}, + "end_time": {"key": "endTime", "type": "iso-8601"}, + "time_grain": {"key": "timeGrain", "type": "str"}, + "unit": {"key": "unit", "type": "str"}, + "name": {"key": "name", "type": "MetricName"}, + "metric_values": {"key": "metricValues", "type": "[PercentileMetricValue]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.start_time = None + self.end_time = None + self.time_grain = None + self.unit = None + self.name = None + self.metric_values = None + + +class PercentileMetricListResult(_serialization.Model): + """The response to a list percentile metrics request. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: The list of percentile metrics for the account. + :vartype value: list[~azure.mgmt.cosmosdb.models.PercentileMetric] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[PercentileMetric]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class PercentileMetricValue(MetricValue): # pylint: disable=too-many-instance-attributes + """Represents percentile metrics values. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar count: The number of values for the metric. + :vartype count: int + :ivar average: The average value of the metric. + :vartype average: float + :ivar maximum: The max value of the metric. + :vartype maximum: float + :ivar minimum: The min value of the metric. + :vartype minimum: float + :ivar timestamp: The metric timestamp (ISO-8601 format). + :vartype timestamp: ~datetime.datetime + :ivar total: The total value of the metric. + :vartype total: float + :ivar p10: The 10th percentile value for the metric. + :vartype p10: float + :ivar p25: The 25th percentile value for the metric. + :vartype p25: float + :ivar p50: The 50th percentile value for the metric. + :vartype p50: float + :ivar p75: The 75th percentile value for the metric. + :vartype p75: float + :ivar p90: The 90th percentile value for the metric. + :vartype p90: float + :ivar p95: The 95th percentile value for the metric. + :vartype p95: float + :ivar p99: The 99th percentile value for the metric. + :vartype p99: float + """ + + _validation = { + "count": {"readonly": True}, + "average": {"readonly": True}, + "maximum": {"readonly": True}, + "minimum": {"readonly": True}, + "timestamp": {"readonly": True}, + "total": {"readonly": True}, + "p10": {"readonly": True}, + "p25": {"readonly": True}, + "p50": {"readonly": True}, + "p75": {"readonly": True}, + "p90": {"readonly": True}, + "p95": {"readonly": True}, + "p99": {"readonly": True}, + } + + _attribute_map = { + "count": {"key": "_count", "type": "int"}, + "average": {"key": "average", "type": "float"}, + "maximum": {"key": "maximum", "type": "float"}, + "minimum": {"key": "minimum", "type": "float"}, + "timestamp": {"key": "timestamp", "type": "iso-8601"}, + "total": {"key": "total", "type": "float"}, + "p10": {"key": "P10", "type": "float"}, + "p25": {"key": "P25", "type": "float"}, + "p50": {"key": "P50", "type": "float"}, + "p75": {"key": "P75", "type": "float"}, + "p90": {"key": "P90", "type": "float"}, + "p95": {"key": "P95", "type": "float"}, + "p99": {"key": "P99", "type": "float"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.p10 = None + self.p25 = None + self.p50 = None + self.p75 = None + self.p90 = None + self.p95 = None + self.p99 = None + + +class PeriodicModeBackupPolicy(BackupPolicy): + """The object representing periodic mode backup policy. + + All required parameters must be populated in order to send to server. + + :ivar type: Describes the mode of backups. Required. Known values are: "Periodic" and + "Continuous". + :vartype type: str or ~azure.mgmt.cosmosdb.models.BackupPolicyType + :ivar migration_state: The object representing the state of the migration between the backup + policies. + :vartype migration_state: ~azure.mgmt.cosmosdb.models.BackupPolicyMigrationState + :ivar periodic_mode_properties: Configuration values for periodic mode backup. + :vartype periodic_mode_properties: ~azure.mgmt.cosmosdb.models.PeriodicModeProperties + """ + + _validation = { + "type": {"required": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "migration_state": {"key": "migrationState", "type": "BackupPolicyMigrationState"}, + "periodic_mode_properties": {"key": "periodicModeProperties", "type": "PeriodicModeProperties"}, + } + + def __init__( + self, + *, + migration_state: Optional["_models.BackupPolicyMigrationState"] = None, + periodic_mode_properties: Optional["_models.PeriodicModeProperties"] = None, + **kwargs: Any + ) -> None: + """ + :keyword migration_state: The object representing the state of the migration between the backup + policies. + :paramtype migration_state: ~azure.mgmt.cosmosdb.models.BackupPolicyMigrationState + :keyword periodic_mode_properties: Configuration values for periodic mode backup. + :paramtype periodic_mode_properties: ~azure.mgmt.cosmosdb.models.PeriodicModeProperties + """ + super().__init__(migration_state=migration_state, **kwargs) + self.type: str = "Periodic" + self.periodic_mode_properties = periodic_mode_properties + + +class PeriodicModeProperties(_serialization.Model): + """Configuration values for periodic mode backup. + + :ivar backup_interval_in_minutes: An integer representing the interval in minutes between two + backups. + :vartype backup_interval_in_minutes: int + :ivar backup_retention_interval_in_hours: An integer representing the time (in hours) that each + backup is retained. + :vartype backup_retention_interval_in_hours: int + :ivar backup_storage_redundancy: Enum to indicate type of backup residency. Known values are: + "Geo", "Local", and "Zone". + :vartype backup_storage_redundancy: str or ~azure.mgmt.cosmosdb.models.BackupStorageRedundancy + """ + + _validation = { + "backup_interval_in_minutes": {"minimum": 0}, + "backup_retention_interval_in_hours": {"minimum": 0}, + } + + _attribute_map = { + "backup_interval_in_minutes": {"key": "backupIntervalInMinutes", "type": "int"}, + "backup_retention_interval_in_hours": {"key": "backupRetentionIntervalInHours", "type": "int"}, + "backup_storage_redundancy": {"key": "backupStorageRedundancy", "type": "str"}, + } + + def __init__( + self, + *, + backup_interval_in_minutes: Optional[int] = None, + backup_retention_interval_in_hours: Optional[int] = None, + backup_storage_redundancy: Optional[Union[str, "_models.BackupStorageRedundancy"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword backup_interval_in_minutes: An integer representing the interval in minutes between + two backups. + :paramtype backup_interval_in_minutes: int + :keyword backup_retention_interval_in_hours: An integer representing the time (in hours) that + each backup is retained. + :paramtype backup_retention_interval_in_hours: int + :keyword backup_storage_redundancy: Enum to indicate type of backup residency. Known values + are: "Geo", "Local", and "Zone". + :paramtype backup_storage_redundancy: str or + ~azure.mgmt.cosmosdb.models.BackupStorageRedundancy + """ + super().__init__(**kwargs) + self.backup_interval_in_minutes = backup_interval_in_minutes + self.backup_retention_interval_in_hours = backup_retention_interval_in_hours + self.backup_storage_redundancy = backup_storage_redundancy + + +class Permission(_serialization.Model): + """The set of data plane operations permitted through this Role Definition. + + :ivar data_actions: An array of data actions that are allowed. + :vartype data_actions: list[str] + :ivar not_data_actions: An array of data actions that are denied. + :vartype not_data_actions: list[str] + """ + + _attribute_map = { + "data_actions": {"key": "dataActions", "type": "[str]"}, + "not_data_actions": {"key": "notDataActions", "type": "[str]"}, + } + + def __init__( + self, *, data_actions: Optional[List[str]] = None, not_data_actions: Optional[List[str]] = None, **kwargs: Any + ) -> None: + """ + :keyword data_actions: An array of data actions that are allowed. + :paramtype data_actions: list[str] + :keyword not_data_actions: An array of data actions that are denied. + :paramtype not_data_actions: list[str] + """ + super().__init__(**kwargs) + self.data_actions = data_actions + self.not_data_actions = not_data_actions + + +class PhysicalPartitionId(_serialization.Model): + """PhysicalPartitionId object. + + All required parameters must be populated in order to send to server. + + :ivar id: Id of a physical partition. Required. + :vartype id: str + """ + + _validation = { + "id": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + } + + def __init__(self, *, id: str, **kwargs: Any) -> None: # pylint: disable=redefined-builtin + """ + :keyword id: Id of a physical partition. Required. + :paramtype id: str + """ + super().__init__(**kwargs) + self.id = id + + +class PhysicalPartitionStorageInfo(_serialization.Model): + """The storage of a physical partition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique identifier of the partition. + :vartype id: str + :ivar storage_in_kb: The storage in KB for the physical partition. + :vartype storage_in_kb: float + """ + + _validation = { + "id": {"readonly": True}, + "storage_in_kb": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "storage_in_kb": {"key": "storageInKB", "type": "float"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.id = None + self.storage_in_kb = None + + +class PhysicalPartitionStorageInfoCollection(_serialization.Model): + """List of physical partitions and their properties returned by a merge operation. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar physical_partition_storage_info_collection: List of physical partitions and their + properties. + :vartype physical_partition_storage_info_collection: + list[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfo] + """ + + _validation = { + "physical_partition_storage_info_collection": {"readonly": True}, + } + + _attribute_map = { + "physical_partition_storage_info_collection": { + "key": "physicalPartitionStorageInfoCollection", + "type": "[PhysicalPartitionStorageInfo]", + }, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.physical_partition_storage_info_collection = None + + +class PhysicalPartitionThroughputInfoProperties(_serialization.Model): # pylint: disable=name-too-long + """The properties of an Azure Cosmos DB PhysicalPartitionThroughputInfoProperties object. + + :ivar physical_partition_throughput_info: Array of physical partition throughput info objects. + :vartype physical_partition_throughput_info: + list[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResource] + """ + + _attribute_map = { + "physical_partition_throughput_info": { + "key": "physicalPartitionThroughputInfo", + "type": "[PhysicalPartitionThroughputInfoResource]", + }, + } + + def __init__( + self, + *, + physical_partition_throughput_info: Optional[List["_models.PhysicalPartitionThroughputInfoResource"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword physical_partition_throughput_info: Array of physical partition throughput info + objects. + :paramtype physical_partition_throughput_info: + list[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResource] + """ + super().__init__(**kwargs) + self.physical_partition_throughput_info = physical_partition_throughput_info + + +class PhysicalPartitionThroughputInfoResource(_serialization.Model): + """PhysicalPartitionThroughputInfo object. + + All required parameters must be populated in order to send to server. + + :ivar id: Id of a physical partition. Required. + :vartype id: str + :ivar throughput: Throughput of a physical partition. + :vartype throughput: float + """ + + _validation = { + "id": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "throughput": {"key": "throughput", "type": "float"}, + } + + def __init__( + self, *, id: str, throughput: Optional[float] = None, **kwargs: Any # pylint: disable=redefined-builtin + ) -> None: + """ + :keyword id: Id of a physical partition. Required. + :paramtype id: str + :keyword throughput: Throughput of a physical partition. + :paramtype throughput: float + """ + super().__init__(**kwargs) + self.id = id + self.throughput = throughput + + +class PhysicalPartitionThroughputInfoResult(ARMResourceProperties): + """An Azure Cosmos DB PhysicalPartitionThroughputInfoResult object. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: properties of physical partition throughput info. + :vartype resource: + ~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResultPropertiesResource + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "PhysicalPartitionThroughputInfoResultPropertiesResource"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + resource: Optional["_models.PhysicalPartitionThroughputInfoResultPropertiesResource"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: properties of physical partition throughput info. + :paramtype resource: + ~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResultPropertiesResource + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + + +class PhysicalPartitionThroughputInfoResultPropertiesResource( + PhysicalPartitionThroughputInfoProperties +): # pylint: disable=name-too-long + """properties of physical partition throughput info. + + :ivar physical_partition_throughput_info: Array of physical partition throughput info objects. + :vartype physical_partition_throughput_info: + list[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResource] + """ + + +class PrivateEndpointConnection(ProxyResource): + """A private endpoint connection. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.cosmosdb.models.SystemData + :ivar private_endpoint: Private endpoint which the connection belongs to. + :vartype private_endpoint: ~azure.mgmt.cosmosdb.models.PrivateEndpointProperty + :ivar private_link_service_connection_state: Connection State of the Private Endpoint + Connection. + :vartype private_link_service_connection_state: + ~azure.mgmt.cosmosdb.models.PrivateLinkServiceConnectionStateProperty + :ivar group_id: Group id of the private endpoint. + :vartype group_id: str + :ivar provisioning_state: Provisioning state of the private endpoint. + :vartype provisioning_state: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "private_endpoint": {"key": "properties.privateEndpoint", "type": "PrivateEndpointProperty"}, + "private_link_service_connection_state": { + "key": "properties.privateLinkServiceConnectionState", + "type": "PrivateLinkServiceConnectionStateProperty", + }, + "group_id": {"key": "properties.groupId", "type": "str"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + } + + def __init__( + self, + *, + private_endpoint: Optional["_models.PrivateEndpointProperty"] = None, + private_link_service_connection_state: Optional["_models.PrivateLinkServiceConnectionStateProperty"] = None, + group_id: Optional[str] = None, + provisioning_state: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword private_endpoint: Private endpoint which the connection belongs to. + :paramtype private_endpoint: ~azure.mgmt.cosmosdb.models.PrivateEndpointProperty + :keyword private_link_service_connection_state: Connection State of the Private Endpoint + Connection. + :paramtype private_link_service_connection_state: + ~azure.mgmt.cosmosdb.models.PrivateLinkServiceConnectionStateProperty + :keyword group_id: Group id of the private endpoint. + :paramtype group_id: str + :keyword provisioning_state: Provisioning state of the private endpoint. + :paramtype provisioning_state: str + """ + super().__init__(**kwargs) + self.private_endpoint = private_endpoint + self.private_link_service_connection_state = private_link_service_connection_state + self.group_id = group_id + self.provisioning_state = provisioning_state + + +class PrivateEndpointConnectionListResult(_serialization.Model): + """A list of private endpoint connections. + + :ivar value: Array of private endpoint connections. + :vartype value: list[~azure.mgmt.cosmosdb.models.PrivateEndpointConnection] + """ + + _attribute_map = { + "value": {"key": "value", "type": "[PrivateEndpointConnection]"}, + } + + def __init__(self, *, value: Optional[List["_models.PrivateEndpointConnection"]] = None, **kwargs: Any) -> None: + """ + :keyword value: Array of private endpoint connections. + :paramtype value: list[~azure.mgmt.cosmosdb.models.PrivateEndpointConnection] + """ + super().__init__(**kwargs) + self.value = value + + +class PrivateEndpointProperty(_serialization.Model): + """Private endpoint which the connection belongs to. + + :ivar id: Resource id of the private endpoint. + :vartype id: str + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + } + + def __init__(self, *, id: Optional[str] = None, **kwargs: Any) -> None: # pylint: disable=redefined-builtin + """ + :keyword id: Resource id of the private endpoint. + :paramtype id: str + """ + super().__init__(**kwargs) + self.id = id + + +class PrivateLinkResource(ARMProxyResource): + """A private link resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the database account. + :vartype id: str + :ivar name: The name of the database account. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar group_id: The private link resource group id. + :vartype group_id: str + :ivar required_members: The private link resource required member names. + :vartype required_members: list[str] + :ivar required_zone_names: The private link resource required zone names. + :vartype required_zone_names: list[str] + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "group_id": {"readonly": True}, + "required_members": {"readonly": True}, + "required_zone_names": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "group_id": {"key": "properties.groupId", "type": "str"}, + "required_members": {"key": "properties.requiredMembers", "type": "[str]"}, + "required_zone_names": {"key": "properties.requiredZoneNames", "type": "[str]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.group_id = None + self.required_members = None + self.required_zone_names = None + + +class PrivateLinkResourceListResult(_serialization.Model): + """A list of private link resources. + + :ivar value: Array of private link resources. + :vartype value: list[~azure.mgmt.cosmosdb.models.PrivateLinkResource] + """ + + _attribute_map = { + "value": {"key": "value", "type": "[PrivateLinkResource]"}, + } + + def __init__(self, *, value: Optional[List["_models.PrivateLinkResource"]] = None, **kwargs: Any) -> None: + """ + :keyword value: Array of private link resources. + :paramtype value: list[~azure.mgmt.cosmosdb.models.PrivateLinkResource] + """ + super().__init__(**kwargs) + self.value = value + + +class PrivateLinkServiceConnectionStateProperty(_serialization.Model): # pylint: disable=name-too-long + """Connection State of the Private Endpoint Connection. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar status: The private link service connection status. + :vartype status: str + :ivar description: The private link service connection description. + :vartype description: str + :ivar actions_required: Any action that is required beyond basic workflow (approve/ reject/ + disconnect). + :vartype actions_required: str + """ + + _validation = { + "actions_required": {"readonly": True}, + } + + _attribute_map = { + "status": {"key": "status", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "actions_required": {"key": "actionsRequired", "type": "str"}, + } + + def __init__(self, *, status: Optional[str] = None, description: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword status: The private link service connection status. + :paramtype status: str + :keyword description: The private link service connection description. + :paramtype description: str + """ + super().__init__(**kwargs) + self.status = status + self.description = description + self.actions_required = None + + +class Privilege(_serialization.Model): + """The set of data plane operations permitted through this Role Definition. + + :ivar resource: An Azure Cosmos DB Mongo DB Resource. + :vartype resource: ~azure.mgmt.cosmosdb.models.PrivilegeResource + :ivar actions: An array of actions that are allowed. + :vartype actions: list[str] + """ + + _attribute_map = { + "resource": {"key": "resource", "type": "PrivilegeResource"}, + "actions": {"key": "actions", "type": "[str]"}, + } + + def __init__( + self, + *, + resource: Optional["_models.PrivilegeResource"] = None, + actions: Optional[List[str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword resource: An Azure Cosmos DB Mongo DB Resource. + :paramtype resource: ~azure.mgmt.cosmosdb.models.PrivilegeResource + :keyword actions: An array of actions that are allowed. + :paramtype actions: list[str] + """ + super().__init__(**kwargs) + self.resource = resource + self.actions = actions + + +class PrivilegeResource(_serialization.Model): + """An Azure Cosmos DB Mongo DB Resource. + + :ivar db: The database name the role is applied. + :vartype db: str + :ivar collection: The collection name the role is applied. + :vartype collection: str + """ + + _attribute_map = { + "db": {"key": "db", "type": "str"}, + "collection": {"key": "collection", "type": "str"}, + } + + def __init__(self, *, db: Optional[str] = None, collection: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword db: The database name the role is applied. + :paramtype db: str + :keyword collection: The collection name the role is applied. + :paramtype collection: str + """ + super().__init__(**kwargs) + self.db = db + self.collection = collection + + +class ProvisioningIssue(_serialization.Model): + """Describes a provisioning issue for a network security perimeter configuration. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: Name of the issue. + :vartype name: str + :ivar properties: Details of a provisioning issue for a network security perimeter (NSP) + configuration. Resource providers should generate separate provisioning issue elements for each + separate issue detected, and include a meaningful and distinctive description, as well as any + appropriate suggestedResourceIds and suggestedAccessRules. + :vartype properties: ~azure.mgmt.cosmosdb.models.ProvisioningIssueProperties + """ + + _validation = { + "name": {"readonly": True}, + "properties": {"readonly": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "properties": {"key": "properties", "type": "ProvisioningIssueProperties"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.name = None + self.properties = None + + +class ProvisioningIssueProperties(_serialization.Model): + """Details of a provisioning issue for a network security perimeter (NSP) configuration. Resource + providers should generate separate provisioning issue elements for each separate issue + detected, and include a meaningful and distinctive description, as well as any appropriate + suggestedResourceIds and suggestedAccessRules. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar issue_type: Type of issue. Known values are: "Unknown", + "ConfigurationPropagationFailure", "MissingPerimeterConfiguration", and + "MissingIdentityConfiguration". + :vartype issue_type: str or ~azure.mgmt.cosmosdb.models.IssueType + :ivar severity: Severity of the issue. Known values are: "Warning" and "Error". + :vartype severity: str or ~azure.mgmt.cosmosdb.models.Severity + :ivar description: Description of the issue. + :vartype description: str + :ivar suggested_resource_ids: Fully qualified resource IDs of suggested resources that can be + associated to the network security perimeter (NSP) to remediate the issue. + :vartype suggested_resource_ids: list[str] + :ivar suggested_access_rules: Access rules that can be added to the network security profile + (NSP) to remediate the issue. + :vartype suggested_access_rules: list[~azure.mgmt.cosmosdb.models.AccessRule] + """ + + _validation = { + "issue_type": {"readonly": True}, + "severity": {"readonly": True}, + "description": {"readonly": True}, + "suggested_resource_ids": {"readonly": True}, + "suggested_access_rules": {"readonly": True}, + } + + _attribute_map = { + "issue_type": {"key": "issueType", "type": "str"}, + "severity": {"key": "severity", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "suggested_resource_ids": {"key": "suggestedResourceIds", "type": "[str]"}, + "suggested_access_rules": {"key": "suggestedAccessRules", "type": "[AccessRule]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.issue_type = None + self.severity = None + self.description = None + self.suggested_resource_ids = None + self.suggested_access_rules = None + + +class RedistributeThroughputParameters(ARMResourceProperties): + """Cosmos DB redistribute throughput parameters object. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: The standard JSON format of a resource throughput. Required. + :vartype resource: ~azure.mgmt.cosmosdb.models.RedistributeThroughputPropertiesResource + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "resource": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "RedistributeThroughputPropertiesResource"}, + } + + def __init__( + self, + *, + resource: "_models.RedistributeThroughputPropertiesResource", + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: The standard JSON format of a resource throughput. Required. + :paramtype resource: ~azure.mgmt.cosmosdb.models.RedistributeThroughputPropertiesResource + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + + +class RedistributeThroughputPropertiesResource(_serialization.Model): + """Resource to redistribute throughput for Azure Cosmos DB resource. + + All required parameters must be populated in order to send to server. + + :ivar throughput_policy: ThroughputPolicy to apply for throughput redistribution. Required. + Known values are: "none", "equal", and "custom". + :vartype throughput_policy: str or ~azure.mgmt.cosmosdb.models.ThroughputPolicyType + :ivar target_physical_partition_throughput_info: Array of + PhysicalPartitionThroughputInfoResource objects. Required. + :vartype target_physical_partition_throughput_info: + list[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResource] + :ivar source_physical_partition_throughput_info: Array of + PhysicalPartitionThroughputInfoResource objects. Required. + :vartype source_physical_partition_throughput_info: + list[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResource] + """ + + _validation = { + "throughput_policy": {"required": True}, + "target_physical_partition_throughput_info": {"required": True}, + "source_physical_partition_throughput_info": {"required": True}, + } + + _attribute_map = { + "throughput_policy": {"key": "throughputPolicy", "type": "str"}, + "target_physical_partition_throughput_info": { + "key": "targetPhysicalPartitionThroughputInfo", + "type": "[PhysicalPartitionThroughputInfoResource]", + }, + "source_physical_partition_throughput_info": { + "key": "sourcePhysicalPartitionThroughputInfo", + "type": "[PhysicalPartitionThroughputInfoResource]", + }, + } + + def __init__( + self, + *, + throughput_policy: Union[str, "_models.ThroughputPolicyType"], + target_physical_partition_throughput_info: List["_models.PhysicalPartitionThroughputInfoResource"], + source_physical_partition_throughput_info: List["_models.PhysicalPartitionThroughputInfoResource"], + **kwargs: Any + ) -> None: + """ + :keyword throughput_policy: ThroughputPolicy to apply for throughput redistribution. Required. + Known values are: "none", "equal", and "custom". + :paramtype throughput_policy: str or ~azure.mgmt.cosmosdb.models.ThroughputPolicyType + :keyword target_physical_partition_throughput_info: Array of + PhysicalPartitionThroughputInfoResource objects. Required. + :paramtype target_physical_partition_throughput_info: + list[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResource] + :keyword source_physical_partition_throughput_info: Array of + PhysicalPartitionThroughputInfoResource objects. Required. + :paramtype source_physical_partition_throughput_info: + list[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResource] + """ + super().__init__(**kwargs) + self.throughput_policy = throughput_policy + self.target_physical_partition_throughput_info = target_physical_partition_throughput_info + self.source_physical_partition_throughput_info = source_physical_partition_throughput_info + + +class RegionForOnlineOffline(_serialization.Model): + """Cosmos DB region to online or offline. + + All required parameters must be populated in order to send to server. + + :ivar region: Cosmos DB region, with spaces between words and each word capitalized. Required. + :vartype region: str + """ + + _validation = { + "region": {"required": True}, + } + + _attribute_map = { + "region": {"key": "region", "type": "str"}, + } + + def __init__(self, *, region: str, **kwargs: Any) -> None: + """ + :keyword region: Cosmos DB region, with spaces between words and each word capitalized. + Required. + :paramtype region: str + """ + super().__init__(**kwargs) + self.region = region + + +class ResourceAssociation(_serialization.Model): + """Information about resource association. + + :ivar name: Name of the resource association. + :vartype name: str + :ivar access_mode: Access mode of the resource association. Known values are: "Enforced", + "Learning", and "Audit". + :vartype access_mode: str or ~azure.mgmt.cosmosdb.models.ResourceAssociationAccessMode + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "access_mode": {"key": "accessMode", "type": "str"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + access_mode: Optional[Union[str, "_models.ResourceAssociationAccessMode"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: Name of the resource association. + :paramtype name: str + :keyword access_mode: Access mode of the resource association. Known values are: "Enforced", + "Learning", and "Audit". + :paramtype access_mode: str or ~azure.mgmt.cosmosdb.models.ResourceAssociationAccessMode + """ + super().__init__(**kwargs) + self.name = name + self.access_mode = access_mode + + +class RestoreParametersBase(_serialization.Model): + """Parameters to indicate the information about the restore. + + :ivar restore_source: The id of the restorable database account from which the restore has to + be initiated. For example: + /subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{restorableDatabaseAccountName}. # pylint: disable=line-too-long + :vartype restore_source: str + :ivar restore_timestamp_in_utc: Time to which the account has to be restored (ISO-8601 format). + :vartype restore_timestamp_in_utc: ~datetime.datetime + :ivar restore_with_ttl_disabled: Specifies whether the restored account will have Time-To-Live + disabled upon the successful restore. + :vartype restore_with_ttl_disabled: bool + """ + + _attribute_map = { + "restore_source": {"key": "restoreSource", "type": "str"}, + "restore_timestamp_in_utc": {"key": "restoreTimestampInUtc", "type": "iso-8601"}, + "restore_with_ttl_disabled": {"key": "restoreWithTtlDisabled", "type": "bool"}, + } + + def __init__( + self, + *, + restore_source: Optional[str] = None, + restore_timestamp_in_utc: Optional[datetime.datetime] = None, + restore_with_ttl_disabled: Optional[bool] = None, + **kwargs: Any + ) -> None: + """ + :keyword restore_source: The id of the restorable database account from which the restore has + to be initiated. For example: + /subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{restorableDatabaseAccountName}. # pylint: disable=line-too-long + :paramtype restore_source: str + :keyword restore_timestamp_in_utc: Time to which the account has to be restored (ISO-8601 + format). + :paramtype restore_timestamp_in_utc: ~datetime.datetime + :keyword restore_with_ttl_disabled: Specifies whether the restored account will have + Time-To-Live disabled upon the successful restore. + :paramtype restore_with_ttl_disabled: bool + """ + super().__init__(**kwargs) + self.restore_source = restore_source + self.restore_timestamp_in_utc = restore_timestamp_in_utc + self.restore_with_ttl_disabled = restore_with_ttl_disabled + + +class ResourceRestoreParameters(RestoreParametersBase): + """Parameters to indicate the information about the restore. + + :ivar restore_source: The id of the restorable database account from which the restore has to + be initiated. For example: + /subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{restorableDatabaseAccountName}. # pylint: disable=line-too-long + :vartype restore_source: str + :ivar restore_timestamp_in_utc: Time to which the account has to be restored (ISO-8601 format). + :vartype restore_timestamp_in_utc: ~datetime.datetime + :ivar restore_with_ttl_disabled: Specifies whether the restored account will have Time-To-Live + disabled upon the successful restore. + :vartype restore_with_ttl_disabled: bool + """ + + +class RestorableDatabaseAccountGetResult(_serialization.Model): + """A Azure Cosmos DB restorable database account. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar account_name: The name of the global database account. + :vartype account_name: str + :ivar creation_time: The creation time of the restorable database account (ISO-8601 format). + :vartype creation_time: ~datetime.datetime + :ivar oldest_restorable_time: The least recent time at which the database account can be + restored to (ISO-8601 format). + :vartype oldest_restorable_time: ~datetime.datetime + :ivar deletion_time: The time at which the restorable database account has been deleted + (ISO-8601 format). + :vartype deletion_time: ~datetime.datetime + :ivar api_type: The API type of the restorable database account. Known values are: "MongoDB", + "Gremlin", "Cassandra", "Table", "Sql", and "GremlinV2". + :vartype api_type: str or ~azure.mgmt.cosmosdb.models.ApiType + :ivar restorable_locations: List of regions where the of the database account can be restored + from. + :vartype restorable_locations: list[~azure.mgmt.cosmosdb.models.RestorableLocationResource] + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "api_type": {"readonly": True}, + "restorable_locations": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "account_name": {"key": "properties.accountName", "type": "str"}, + "creation_time": {"key": "properties.creationTime", "type": "iso-8601"}, + "oldest_restorable_time": {"key": "properties.oldestRestorableTime", "type": "iso-8601"}, + "deletion_time": {"key": "properties.deletionTime", "type": "iso-8601"}, + "api_type": {"key": "properties.apiType", "type": "str"}, + "restorable_locations": {"key": "properties.restorableLocations", "type": "[RestorableLocationResource]"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + account_name: Optional[str] = None, + creation_time: Optional[datetime.datetime] = None, + oldest_restorable_time: Optional[datetime.datetime] = None, + deletion_time: Optional[datetime.datetime] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword account_name: The name of the global database account. + :paramtype account_name: str + :keyword creation_time: The creation time of the restorable database account (ISO-8601 format). + :paramtype creation_time: ~datetime.datetime + :keyword oldest_restorable_time: The least recent time at which the database account can be + restored to (ISO-8601 format). + :paramtype oldest_restorable_time: ~datetime.datetime + :keyword deletion_time: The time at which the restorable database account has been deleted + (ISO-8601 format). + :paramtype deletion_time: ~datetime.datetime + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.location = location + self.account_name = account_name + self.creation_time = creation_time + self.oldest_restorable_time = oldest_restorable_time + self.deletion_time = deletion_time + self.api_type = None + self.restorable_locations = None + + +class RestorableDatabaseAccountsListResult(_serialization.Model): + """The List operation response, that contains the restorable database accounts and their + properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of restorable database accounts and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.RestorableDatabaseAccountGetResult] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[RestorableDatabaseAccountGetResult]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class RestorableGremlinDatabaseGetResult(_serialization.Model): + """An Azure Cosmos DB Gremlin database event. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource Identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar resource: The resource of an Azure Cosmos DB Gremlin database event. + :vartype resource: ~azure.mgmt.cosmosdb.models.RestorableGremlinDatabasePropertiesResource + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "resource": {"key": "properties.resource", "type": "RestorableGremlinDatabasePropertiesResource"}, + } + + def __init__( + self, *, resource: Optional["_models.RestorableGremlinDatabasePropertiesResource"] = None, **kwargs: Any + ) -> None: + """ + :keyword resource: The resource of an Azure Cosmos DB Gremlin database event. + :paramtype resource: ~azure.mgmt.cosmosdb.models.RestorableGremlinDatabasePropertiesResource + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.resource = resource + + +class RestorableGremlinDatabasePropertiesResource(_serialization.Model): # pylint: disable=name-too-long + """The resource of an Azure Cosmos DB Gremlin database event. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar rid: A system generated property. A unique identifier. + :vartype rid: str + :ivar operation_type: The operation type of this database event. Known values are: "Create", + "Replace", "Delete", "Recreate", and "SystemOperation". + :vartype operation_type: str or ~azure.mgmt.cosmosdb.models.OperationType + :ivar can_undelete: A state of this database to identify if this database is restorable in same + account. + :vartype can_undelete: str + :ivar can_undelete_reason: The reason why this database can not be restored in same account. + :vartype can_undelete_reason: str + :ivar event_timestamp: The time when this database event happened. + :vartype event_timestamp: str + :ivar owner_id: The name of this Gremlin database. + :vartype owner_id: str + :ivar owner_resource_id: The resource ID of this Gremlin database. + :vartype owner_resource_id: str + """ + + _validation = { + "rid": {"readonly": True}, + "operation_type": {"readonly": True}, + "can_undelete": {"readonly": True}, + "can_undelete_reason": {"readonly": True}, + "event_timestamp": {"readonly": True}, + "owner_id": {"readonly": True}, + "owner_resource_id": {"readonly": True}, + } + + _attribute_map = { + "rid": {"key": "_rid", "type": "str"}, + "operation_type": {"key": "operationType", "type": "str"}, + "can_undelete": {"key": "canUndelete", "type": "str"}, + "can_undelete_reason": {"key": "canUndeleteReason", "type": "str"}, + "event_timestamp": {"key": "eventTimestamp", "type": "str"}, + "owner_id": {"key": "ownerId", "type": "str"}, + "owner_resource_id": {"key": "ownerResourceId", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.rid = None + self.operation_type = None + self.can_undelete = None + self.can_undelete_reason = None + self.event_timestamp = None + self.owner_id = None + self.owner_resource_id = None + + +class RestorableGremlinDatabasesListResult(_serialization.Model): + """The List operation response, that contains the Gremlin database events and their properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of Gremlin database events and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.RestorableGremlinDatabaseGetResult] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[RestorableGremlinDatabaseGetResult]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class RestorableGremlinGraphGetResult(_serialization.Model): + """An Azure Cosmos DB Gremlin graph event. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource Identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar resource: The resource of an Azure Cosmos DB Gremlin graph event. + :vartype resource: ~azure.mgmt.cosmosdb.models.RestorableGremlinGraphPropertiesResource + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "resource": {"key": "properties.resource", "type": "RestorableGremlinGraphPropertiesResource"}, + } + + def __init__( + self, *, resource: Optional["_models.RestorableGremlinGraphPropertiesResource"] = None, **kwargs: Any + ) -> None: + """ + :keyword resource: The resource of an Azure Cosmos DB Gremlin graph event. + :paramtype resource: ~azure.mgmt.cosmosdb.models.RestorableGremlinGraphPropertiesResource + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.resource = resource + + +class RestorableGremlinGraphPropertiesResource(_serialization.Model): + """The resource of an Azure Cosmos DB Gremlin graph event. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar rid: A system generated property. A unique identifier. + :vartype rid: str + :ivar operation_type: The operation type of this graph event. Known values are: "Create", + "Replace", "Delete", "Recreate", and "SystemOperation". + :vartype operation_type: str or ~azure.mgmt.cosmosdb.models.OperationType + :ivar can_undelete: A state of this graph to identify if this graph is restorable in same + account. + :vartype can_undelete: str + :ivar can_undelete_reason: The reason why this graph can not be restored in same account. + :vartype can_undelete_reason: str + :ivar event_timestamp: The time when this graph event happened. + :vartype event_timestamp: str + :ivar owner_id: The name of this Gremlin graph. + :vartype owner_id: str + :ivar owner_resource_id: The resource ID of this Gremlin graph. + :vartype owner_resource_id: str + """ + + _validation = { + "rid": {"readonly": True}, + "operation_type": {"readonly": True}, + "can_undelete": {"readonly": True}, + "can_undelete_reason": {"readonly": True}, + "event_timestamp": {"readonly": True}, + "owner_id": {"readonly": True}, + "owner_resource_id": {"readonly": True}, + } + + _attribute_map = { + "rid": {"key": "_rid", "type": "str"}, + "operation_type": {"key": "operationType", "type": "str"}, + "can_undelete": {"key": "canUndelete", "type": "str"}, + "can_undelete_reason": {"key": "canUndeleteReason", "type": "str"}, + "event_timestamp": {"key": "eventTimestamp", "type": "str"}, + "owner_id": {"key": "ownerId", "type": "str"}, + "owner_resource_id": {"key": "ownerResourceId", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.rid = None + self.operation_type = None + self.can_undelete = None + self.can_undelete_reason = None + self.event_timestamp = None + self.owner_id = None + self.owner_resource_id = None + + +class RestorableGremlinGraphsListResult(_serialization.Model): + """The List operation response, that contains the Gremlin graph events and their properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of Gremlin graph events and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.RestorableGremlinGraphGetResult] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[RestorableGremlinGraphGetResult]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class RestorableGremlinResourcesGetResult(_serialization.Model): + """Specific Databases to restore. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar database_name: The name of the gremlin database available for restore. + :vartype database_name: str + :ivar graph_names: The names of the graphs available for restore. + :vartype graph_names: list[str] + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "database_name": {"key": "databaseName", "type": "str"}, + "graph_names": {"key": "graphNames", "type": "[str]"}, + } + + def __init__( + self, *, database_name: Optional[str] = None, graph_names: Optional[List[str]] = None, **kwargs: Any + ) -> None: + """ + :keyword database_name: The name of the gremlin database available for restore. + :paramtype database_name: str + :keyword graph_names: The names of the graphs available for restore. + :paramtype graph_names: list[str] + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.database_name = database_name + self.graph_names = graph_names + + +class RestorableGremlinResourcesListResult(_serialization.Model): + """The List operation response, that contains the restorable Gremlin resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of restorable Gremlin resources, including the gremlin database and graph + names. + :vartype value: list[~azure.mgmt.cosmosdb.models.RestorableGremlinResourcesGetResult] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[RestorableGremlinResourcesGetResult]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class RestorableLocationResource(_serialization.Model): + """Properties of the regional restorable account. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar location_name: The location of the regional restorable account. + :vartype location_name: str + :ivar regional_database_account_instance_id: The instance id of the regional restorable + account. + :vartype regional_database_account_instance_id: str + :ivar creation_time: The creation time of the regional restorable database account (ISO-8601 + format). + :vartype creation_time: ~datetime.datetime + :ivar deletion_time: The time at which the regional restorable database account has been + deleted (ISO-8601 format). + :vartype deletion_time: ~datetime.datetime + """ + + _validation = { + "location_name": {"readonly": True}, + "regional_database_account_instance_id": {"readonly": True}, + "creation_time": {"readonly": True}, + "deletion_time": {"readonly": True}, + } + + _attribute_map = { + "location_name": {"key": "locationName", "type": "str"}, + "regional_database_account_instance_id": {"key": "regionalDatabaseAccountInstanceId", "type": "str"}, + "creation_time": {"key": "creationTime", "type": "iso-8601"}, + "deletion_time": {"key": "deletionTime", "type": "iso-8601"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.location_name = None + self.regional_database_account_instance_id = None + self.creation_time = None + self.deletion_time = None + + +class RestorableMongodbCollectionGetResult(_serialization.Model): + """An Azure Cosmos DB MongoDB collection event. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource Identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar resource: The resource of an Azure Cosmos DB MongoDB collection event. + :vartype resource: ~azure.mgmt.cosmosdb.models.RestorableMongodbCollectionPropertiesResource + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "resource": {"key": "properties.resource", "type": "RestorableMongodbCollectionPropertiesResource"}, + } + + def __init__( + self, *, resource: Optional["_models.RestorableMongodbCollectionPropertiesResource"] = None, **kwargs: Any + ) -> None: + """ + :keyword resource: The resource of an Azure Cosmos DB MongoDB collection event. + :paramtype resource: ~azure.mgmt.cosmosdb.models.RestorableMongodbCollectionPropertiesResource + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.resource = resource + + +class RestorableMongodbCollectionPropertiesResource(_serialization.Model): # pylint: disable=name-too-long + """The resource of an Azure Cosmos DB MongoDB collection event. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar rid: A system generated property. A unique identifier. + :vartype rid: str + :ivar operation_type: The operation type of this collection event. Known values are: "Create", + "Replace", "Delete", "Recreate", and "SystemOperation". + :vartype operation_type: str or ~azure.mgmt.cosmosdb.models.OperationType + :ivar can_undelete: A state of this collection to identify if this container is restorable in + same account. + :vartype can_undelete: str + :ivar can_undelete_reason: The reason why this collection can not be restored in same account. + :vartype can_undelete_reason: str + :ivar event_timestamp: The time when this collection event happened. + :vartype event_timestamp: str + :ivar owner_id: The name of this MongoDB collection. + :vartype owner_id: str + :ivar owner_resource_id: The resource ID of this MongoDB collection. + :vartype owner_resource_id: str + """ + + _validation = { + "rid": {"readonly": True}, + "operation_type": {"readonly": True}, + "can_undelete": {"readonly": True}, + "can_undelete_reason": {"readonly": True}, + "event_timestamp": {"readonly": True}, + "owner_id": {"readonly": True}, + "owner_resource_id": {"readonly": True}, + } + + _attribute_map = { + "rid": {"key": "_rid", "type": "str"}, + "operation_type": {"key": "operationType", "type": "str"}, + "can_undelete": {"key": "canUndelete", "type": "str"}, + "can_undelete_reason": {"key": "canUndeleteReason", "type": "str"}, + "event_timestamp": {"key": "eventTimestamp", "type": "str"}, + "owner_id": {"key": "ownerId", "type": "str"}, + "owner_resource_id": {"key": "ownerResourceId", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.rid = None + self.operation_type = None + self.can_undelete = None + self.can_undelete_reason = None + self.event_timestamp = None + self.owner_id = None + self.owner_resource_id = None + + +class RestorableMongodbCollectionsListResult(_serialization.Model): + """The List operation response, that contains the MongoDB collection events and their properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of MongoDB collection events and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.RestorableMongodbCollectionGetResult] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[RestorableMongodbCollectionGetResult]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class RestorableMongodbDatabaseGetResult(_serialization.Model): + """An Azure Cosmos DB MongoDB database event. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource Identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar resource: The resource of an Azure Cosmos DB MongoDB database event. + :vartype resource: ~azure.mgmt.cosmosdb.models.RestorableMongodbDatabasePropertiesResource + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "resource": {"key": "properties.resource", "type": "RestorableMongodbDatabasePropertiesResource"}, + } + + def __init__( + self, *, resource: Optional["_models.RestorableMongodbDatabasePropertiesResource"] = None, **kwargs: Any + ) -> None: + """ + :keyword resource: The resource of an Azure Cosmos DB MongoDB database event. + :paramtype resource: ~azure.mgmt.cosmosdb.models.RestorableMongodbDatabasePropertiesResource + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.resource = resource + + +class RestorableMongodbDatabasePropertiesResource(_serialization.Model): # pylint: disable=name-too-long + """The resource of an Azure Cosmos DB MongoDB database event. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar rid: A system generated property. A unique identifier. + :vartype rid: str + :ivar operation_type: The operation type of this database event. Known values are: "Create", + "Replace", "Delete", "Recreate", and "SystemOperation". + :vartype operation_type: str or ~azure.mgmt.cosmosdb.models.OperationType + :ivar can_undelete: A state of this database to identify if this database is restorable in same + account. + :vartype can_undelete: str + :ivar can_undelete_reason: The reason why this database can not be restored in same account. + :vartype can_undelete_reason: str + :ivar event_timestamp: The time when this database event happened. + :vartype event_timestamp: str + :ivar owner_id: The name of this MongoDB database. + :vartype owner_id: str + :ivar owner_resource_id: The resource ID of this MongoDB database. + :vartype owner_resource_id: str + """ + + _validation = { + "rid": {"readonly": True}, + "operation_type": {"readonly": True}, + "can_undelete": {"readonly": True}, + "can_undelete_reason": {"readonly": True}, + "event_timestamp": {"readonly": True}, + "owner_id": {"readonly": True}, + "owner_resource_id": {"readonly": True}, + } + + _attribute_map = { + "rid": {"key": "_rid", "type": "str"}, + "operation_type": {"key": "operationType", "type": "str"}, + "can_undelete": {"key": "canUndelete", "type": "str"}, + "can_undelete_reason": {"key": "canUndeleteReason", "type": "str"}, + "event_timestamp": {"key": "eventTimestamp", "type": "str"}, + "owner_id": {"key": "ownerId", "type": "str"}, + "owner_resource_id": {"key": "ownerResourceId", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.rid = None + self.operation_type = None + self.can_undelete = None + self.can_undelete_reason = None + self.event_timestamp = None + self.owner_id = None + self.owner_resource_id = None + + +class RestorableMongodbDatabasesListResult(_serialization.Model): + """The List operation response, that contains the MongoDB database events and their properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of MongoDB database events and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.RestorableMongodbDatabaseGetResult] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[RestorableMongodbDatabaseGetResult]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class RestorableMongodbResourcesGetResult(_serialization.Model): + """Specific Databases to restore. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar database_name: The name of the database available for restore. + :vartype database_name: str + :ivar collection_names: The names of the collections available for restore. + :vartype collection_names: list[str] + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "database_name": {"key": "databaseName", "type": "str"}, + "collection_names": {"key": "collectionNames", "type": "[str]"}, + } + + def __init__( + self, *, database_name: Optional[str] = None, collection_names: Optional[List[str]] = None, **kwargs: Any + ) -> None: + """ + :keyword database_name: The name of the database available for restore. + :paramtype database_name: str + :keyword collection_names: The names of the collections available for restore. + :paramtype collection_names: list[str] + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.database_name = database_name + self.collection_names = collection_names + + +class RestorableMongodbResourcesListResult(_serialization.Model): + """The List operation response, that contains the restorable MongoDB resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of restorable MongoDB resources, including the database and collection names. + :vartype value: list[~azure.mgmt.cosmosdb.models.RestorableMongodbResourcesGetResult] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[RestorableMongodbResourcesGetResult]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class RestorableSqlContainerGetResult(_serialization.Model): + """An Azure Cosmos DB SQL container event. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource Identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar resource: The resource of an Azure Cosmos DB SQL container event. + :vartype resource: ~azure.mgmt.cosmosdb.models.RestorableSqlContainerPropertiesResource + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "resource": {"key": "properties.resource", "type": "RestorableSqlContainerPropertiesResource"}, + } + + def __init__( + self, *, resource: Optional["_models.RestorableSqlContainerPropertiesResource"] = None, **kwargs: Any + ) -> None: + """ + :keyword resource: The resource of an Azure Cosmos DB SQL container event. + :paramtype resource: ~azure.mgmt.cosmosdb.models.RestorableSqlContainerPropertiesResource + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.resource = resource + + +class RestorableSqlContainerPropertiesResource(_serialization.Model): + """The resource of an Azure Cosmos DB SQL container event. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar rid: A system generated property. A unique identifier. + :vartype rid: str + :ivar operation_type: The operation type of this container event. Known values are: "Create", + "Replace", "Delete", "Recreate", and "SystemOperation". + :vartype operation_type: str or ~azure.mgmt.cosmosdb.models.OperationType + :ivar can_undelete: A state of this container to identify if this container is restorable in + same account. + :vartype can_undelete: str + :ivar can_undelete_reason: The reason why this container can not be restored in same account. + :vartype can_undelete_reason: str + :ivar event_timestamp: The when this container event happened. + :vartype event_timestamp: str + :ivar owner_id: The name of this SQL container. + :vartype owner_id: str + :ivar owner_resource_id: The resource ID of this SQL container. + :vartype owner_resource_id: str + :ivar container: Cosmos DB SQL container resource object. + :vartype container: + ~azure.mgmt.cosmosdb.models.RestorableSqlContainerPropertiesResourceContainer + """ + + _validation = { + "rid": {"readonly": True}, + "operation_type": {"readonly": True}, + "can_undelete": {"readonly": True}, + "can_undelete_reason": {"readonly": True}, + "event_timestamp": {"readonly": True}, + "owner_id": {"readonly": True}, + "owner_resource_id": {"readonly": True}, + } + + _attribute_map = { + "rid": {"key": "_rid", "type": "str"}, + "operation_type": {"key": "operationType", "type": "str"}, + "can_undelete": {"key": "canUndelete", "type": "str"}, + "can_undelete_reason": {"key": "canUndeleteReason", "type": "str"}, + "event_timestamp": {"key": "eventTimestamp", "type": "str"}, + "owner_id": {"key": "ownerId", "type": "str"}, + "owner_resource_id": {"key": "ownerResourceId", "type": "str"}, + "container": {"key": "container", "type": "RestorableSqlContainerPropertiesResourceContainer"}, + } + + def __init__( + self, *, container: Optional["_models.RestorableSqlContainerPropertiesResourceContainer"] = None, **kwargs: Any + ) -> None: + """ + :keyword container: Cosmos DB SQL container resource object. + :paramtype container: + ~azure.mgmt.cosmosdb.models.RestorableSqlContainerPropertiesResourceContainer + """ + super().__init__(**kwargs) + self.rid = None + self.operation_type = None + self.can_undelete = None + self.can_undelete_reason = None + self.event_timestamp = None + self.owner_id = None + self.owner_resource_id = None + self.container = container + + +class SqlContainerResource(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Cosmos DB SQL container resource object. + + All required parameters must be populated in order to send to server. + + :ivar id: Name of the Cosmos DB SQL container. Required. + :vartype id: str + :ivar indexing_policy: The configuration of the indexing policy. By default, the indexing is + automatic for all document paths within the container. + :vartype indexing_policy: ~azure.mgmt.cosmosdb.models.IndexingPolicy + :ivar partition_key: The configuration of the partition key to be used for partitioning data + into multiple partitions. + :vartype partition_key: ~azure.mgmt.cosmosdb.models.ContainerPartitionKey + :ivar default_ttl: Default time to live. + :vartype default_ttl: int + :ivar unique_key_policy: The unique key policy configuration for specifying uniqueness + constraints on documents in the collection in the Azure Cosmos DB service. + :vartype unique_key_policy: ~azure.mgmt.cosmosdb.models.UniqueKeyPolicy + :ivar conflict_resolution_policy: The conflict resolution policy for the container. + :vartype conflict_resolution_policy: ~azure.mgmt.cosmosdb.models.ConflictResolutionPolicy + :ivar client_encryption_policy: The client encryption policy for the container. + :vartype client_encryption_policy: ~azure.mgmt.cosmosdb.models.ClientEncryptionPolicy + :ivar analytical_storage_ttl: Analytical TTL. + :vartype analytical_storage_ttl: int + :ivar restore_parameters: Parameters to indicate the information about the restore. + :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" + and "Restore". + :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + :ivar materialized_view_definition: The configuration for defining Materialized Views. This + must be specified only for creating a Materialized View container. + :vartype materialized_view_definition: ~azure.mgmt.cosmosdb.models.MaterializedViewDefinition + :ivar computed_properties: List of computed properties. + :vartype computed_properties: list[~azure.mgmt.cosmosdb.models.ComputedProperty] + """ + + _validation = { + "id": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "indexing_policy": {"key": "indexingPolicy", "type": "IndexingPolicy"}, + "partition_key": {"key": "partitionKey", "type": "ContainerPartitionKey"}, + "default_ttl": {"key": "defaultTtl", "type": "int"}, + "unique_key_policy": {"key": "uniqueKeyPolicy", "type": "UniqueKeyPolicy"}, + "conflict_resolution_policy": {"key": "conflictResolutionPolicy", "type": "ConflictResolutionPolicy"}, + "client_encryption_policy": {"key": "clientEncryptionPolicy", "type": "ClientEncryptionPolicy"}, + "analytical_storage_ttl": {"key": "analyticalStorageTtl", "type": "int"}, + "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, + "create_mode": {"key": "createMode", "type": "str"}, + "materialized_view_definition": {"key": "materializedViewDefinition", "type": "MaterializedViewDefinition"}, + "computed_properties": {"key": "computedProperties", "type": "[ComputedProperty]"}, + } + + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + indexing_policy: Optional["_models.IndexingPolicy"] = None, + partition_key: Optional["_models.ContainerPartitionKey"] = None, + default_ttl: Optional[int] = None, + unique_key_policy: Optional["_models.UniqueKeyPolicy"] = None, + conflict_resolution_policy: Optional["_models.ConflictResolutionPolicy"] = None, + client_encryption_policy: Optional["_models.ClientEncryptionPolicy"] = None, + analytical_storage_ttl: Optional[int] = None, + restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, + create_mode: Union[str, "_models.CreateMode"] = "Default", + materialized_view_definition: Optional["_models.MaterializedViewDefinition"] = None, + computed_properties: Optional[List["_models.ComputedProperty"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword id: Name of the Cosmos DB SQL container. Required. + :paramtype id: str + :keyword indexing_policy: The configuration of the indexing policy. By default, the indexing is + automatic for all document paths within the container. + :paramtype indexing_policy: ~azure.mgmt.cosmosdb.models.IndexingPolicy + :keyword partition_key: The configuration of the partition key to be used for partitioning data + into multiple partitions. + :paramtype partition_key: ~azure.mgmt.cosmosdb.models.ContainerPartitionKey + :keyword default_ttl: Default time to live. + :paramtype default_ttl: int + :keyword unique_key_policy: The unique key policy configuration for specifying uniqueness + constraints on documents in the collection in the Azure Cosmos DB service. + :paramtype unique_key_policy: ~azure.mgmt.cosmosdb.models.UniqueKeyPolicy + :keyword conflict_resolution_policy: The conflict resolution policy for the container. + :paramtype conflict_resolution_policy: ~azure.mgmt.cosmosdb.models.ConflictResolutionPolicy + :keyword client_encryption_policy: The client encryption policy for the container. + :paramtype client_encryption_policy: ~azure.mgmt.cosmosdb.models.ClientEncryptionPolicy + :keyword analytical_storage_ttl: Analytical TTL. + :paramtype analytical_storage_ttl: int + :keyword restore_parameters: Parameters to indicate the information about the restore. + :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: + "Default" and "Restore". + :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + :keyword materialized_view_definition: The configuration for defining Materialized Views. This + must be specified only for creating a Materialized View container. + :paramtype materialized_view_definition: ~azure.mgmt.cosmosdb.models.MaterializedViewDefinition + :keyword computed_properties: List of computed properties. + :paramtype computed_properties: list[~azure.mgmt.cosmosdb.models.ComputedProperty] + """ + super().__init__(**kwargs) + self.id = id + self.indexing_policy = indexing_policy + self.partition_key = partition_key + self.default_ttl = default_ttl + self.unique_key_policy = unique_key_policy + self.conflict_resolution_policy = conflict_resolution_policy + self.client_encryption_policy = client_encryption_policy + self.analytical_storage_ttl = analytical_storage_ttl + self.restore_parameters = restore_parameters + self.create_mode = create_mode + self.materialized_view_definition = materialized_view_definition + self.computed_properties = computed_properties + + +class RestorableSqlContainerPropertiesResourceContainer( + SqlContainerResource, ExtendedResourceProperties +): # pylint: disable=too-many-instance-attributes,name-too-long + """Cosmos DB SQL container resource object. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar rid: A system generated property. A unique identifier. + :vartype rid: str + :ivar ts: A system generated property that denotes the last updated timestamp of the resource. + :vartype ts: float + :ivar etag: A system generated property representing the resource etag required for optimistic + concurrency control. + :vartype etag: str + :ivar id: Name of the Cosmos DB SQL container. Required. + :vartype id: str + :ivar indexing_policy: The configuration of the indexing policy. By default, the indexing is + automatic for all document paths within the container. + :vartype indexing_policy: ~azure.mgmt.cosmosdb.models.IndexingPolicy + :ivar partition_key: The configuration of the partition key to be used for partitioning data + into multiple partitions. + :vartype partition_key: ~azure.mgmt.cosmosdb.models.ContainerPartitionKey + :ivar default_ttl: Default time to live. + :vartype default_ttl: int + :ivar unique_key_policy: The unique key policy configuration for specifying uniqueness + constraints on documents in the collection in the Azure Cosmos DB service. + :vartype unique_key_policy: ~azure.mgmt.cosmosdb.models.UniqueKeyPolicy + :ivar conflict_resolution_policy: The conflict resolution policy for the container. + :vartype conflict_resolution_policy: ~azure.mgmt.cosmosdb.models.ConflictResolutionPolicy + :ivar client_encryption_policy: The client encryption policy for the container. + :vartype client_encryption_policy: ~azure.mgmt.cosmosdb.models.ClientEncryptionPolicy + :ivar analytical_storage_ttl: Analytical TTL. + :vartype analytical_storage_ttl: int + :ivar restore_parameters: Parameters to indicate the information about the restore. + :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" + and "Restore". + :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + :ivar materialized_view_definition: The configuration for defining Materialized Views. This + must be specified only for creating a Materialized View container. + :vartype materialized_view_definition: ~azure.mgmt.cosmosdb.models.MaterializedViewDefinition + :ivar computed_properties: List of computed properties. + :vartype computed_properties: list[~azure.mgmt.cosmosdb.models.ComputedProperty] + :ivar self_property: A system generated property that specifies the addressable path of the + container resource. + :vartype self_property: str + """ + + _validation = { + "rid": {"readonly": True}, + "ts": {"readonly": True}, + "etag": {"readonly": True}, + "id": {"required": True}, + "self_property": {"readonly": True}, + } + + _attribute_map = { + "rid": {"key": "_rid", "type": "str"}, + "ts": {"key": "_ts", "type": "float"}, + "etag": {"key": "_etag", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "indexing_policy": {"key": "indexingPolicy", "type": "IndexingPolicy"}, + "partition_key": {"key": "partitionKey", "type": "ContainerPartitionKey"}, + "default_ttl": {"key": "defaultTtl", "type": "int"}, + "unique_key_policy": {"key": "uniqueKeyPolicy", "type": "UniqueKeyPolicy"}, + "conflict_resolution_policy": {"key": "conflictResolutionPolicy", "type": "ConflictResolutionPolicy"}, + "client_encryption_policy": {"key": "clientEncryptionPolicy", "type": "ClientEncryptionPolicy"}, + "analytical_storage_ttl": {"key": "analyticalStorageTtl", "type": "int"}, + "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, + "create_mode": {"key": "createMode", "type": "str"}, + "materialized_view_definition": {"key": "materializedViewDefinition", "type": "MaterializedViewDefinition"}, + "computed_properties": {"key": "computedProperties", "type": "[ComputedProperty]"}, + "self_property": {"key": "_self", "type": "str"}, + } + + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + indexing_policy: Optional["_models.IndexingPolicy"] = None, + partition_key: Optional["_models.ContainerPartitionKey"] = None, + default_ttl: Optional[int] = None, + unique_key_policy: Optional["_models.UniqueKeyPolicy"] = None, + conflict_resolution_policy: Optional["_models.ConflictResolutionPolicy"] = None, + client_encryption_policy: Optional["_models.ClientEncryptionPolicy"] = None, + analytical_storage_ttl: Optional[int] = None, + restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, + create_mode: Union[str, "_models.CreateMode"] = "Default", + materialized_view_definition: Optional["_models.MaterializedViewDefinition"] = None, + computed_properties: Optional[List["_models.ComputedProperty"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword id: Name of the Cosmos DB SQL container. Required. + :paramtype id: str + :keyword indexing_policy: The configuration of the indexing policy. By default, the indexing is + automatic for all document paths within the container. + :paramtype indexing_policy: ~azure.mgmt.cosmosdb.models.IndexingPolicy + :keyword partition_key: The configuration of the partition key to be used for partitioning data + into multiple partitions. + :paramtype partition_key: ~azure.mgmt.cosmosdb.models.ContainerPartitionKey + :keyword default_ttl: Default time to live. + :paramtype default_ttl: int + :keyword unique_key_policy: The unique key policy configuration for specifying uniqueness + constraints on documents in the collection in the Azure Cosmos DB service. + :paramtype unique_key_policy: ~azure.mgmt.cosmosdb.models.UniqueKeyPolicy + :keyword conflict_resolution_policy: The conflict resolution policy for the container. + :paramtype conflict_resolution_policy: ~azure.mgmt.cosmosdb.models.ConflictResolutionPolicy + :keyword client_encryption_policy: The client encryption policy for the container. + :paramtype client_encryption_policy: ~azure.mgmt.cosmosdb.models.ClientEncryptionPolicy + :keyword analytical_storage_ttl: Analytical TTL. + :paramtype analytical_storage_ttl: int + :keyword restore_parameters: Parameters to indicate the information about the restore. + :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: + "Default" and "Restore". + :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + :keyword materialized_view_definition: The configuration for defining Materialized Views. This + must be specified only for creating a Materialized View container. + :paramtype materialized_view_definition: ~azure.mgmt.cosmosdb.models.MaterializedViewDefinition + :keyword computed_properties: List of computed properties. + :paramtype computed_properties: list[~azure.mgmt.cosmosdb.models.ComputedProperty] + """ + super().__init__( + id=id, + indexing_policy=indexing_policy, + partition_key=partition_key, + default_ttl=default_ttl, + unique_key_policy=unique_key_policy, + conflict_resolution_policy=conflict_resolution_policy, + client_encryption_policy=client_encryption_policy, + analytical_storage_ttl=analytical_storage_ttl, + restore_parameters=restore_parameters, + create_mode=create_mode, + materialized_view_definition=materialized_view_definition, + computed_properties=computed_properties, + **kwargs + ) + self.rid = None + self.ts = None + self.etag = None + self.self_property = None + self.id = id + self.indexing_policy = indexing_policy + self.partition_key = partition_key + self.default_ttl = default_ttl + self.unique_key_policy = unique_key_policy + self.conflict_resolution_policy = conflict_resolution_policy + self.client_encryption_policy = client_encryption_policy + self.analytical_storage_ttl = analytical_storage_ttl + self.restore_parameters = restore_parameters + self.create_mode = create_mode + self.materialized_view_definition = materialized_view_definition + self.computed_properties = computed_properties + + +class RestorableSqlContainersListResult(_serialization.Model): + """The List operation response, that contains the SQL container events and their properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of SQL container events and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.RestorableSqlContainerGetResult] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[RestorableSqlContainerGetResult]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class RestorableSqlDatabaseGetResult(_serialization.Model): + """An Azure Cosmos DB SQL database event. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource Identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar resource: The resource of an Azure Cosmos DB SQL database event. + :vartype resource: ~azure.mgmt.cosmosdb.models.RestorableSqlDatabasePropertiesResource + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "resource": {"key": "properties.resource", "type": "RestorableSqlDatabasePropertiesResource"}, + } + + def __init__( + self, *, resource: Optional["_models.RestorableSqlDatabasePropertiesResource"] = None, **kwargs: Any + ) -> None: + """ + :keyword resource: The resource of an Azure Cosmos DB SQL database event. + :paramtype resource: ~azure.mgmt.cosmosdb.models.RestorableSqlDatabasePropertiesResource + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.resource = resource + + +class RestorableSqlDatabasePropertiesResource(_serialization.Model): + """The resource of an Azure Cosmos DB SQL database event. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar rid: A system generated property. A unique identifier. + :vartype rid: str + :ivar operation_type: The operation type of this database event. Known values are: "Create", + "Replace", "Delete", "Recreate", and "SystemOperation". + :vartype operation_type: str or ~azure.mgmt.cosmosdb.models.OperationType + :ivar can_undelete: A state of this database to identify if this database is restorable in same + account. + :vartype can_undelete: str + :ivar can_undelete_reason: The reason why this database can not be restored in same account. + :vartype can_undelete_reason: str + :ivar event_timestamp: The time when this database event happened. + :vartype event_timestamp: str + :ivar owner_id: The name of the SQL database. + :vartype owner_id: str + :ivar owner_resource_id: The resource ID of the SQL database. + :vartype owner_resource_id: str + :ivar database: Cosmos DB SQL database resource object. + :vartype database: ~azure.mgmt.cosmosdb.models.RestorableSqlDatabasePropertiesResourceDatabase + """ + + _validation = { + "rid": {"readonly": True}, + "operation_type": {"readonly": True}, + "can_undelete": {"readonly": True}, + "can_undelete_reason": {"readonly": True}, + "event_timestamp": {"readonly": True}, + "owner_id": {"readonly": True}, + "owner_resource_id": {"readonly": True}, + } + + _attribute_map = { + "rid": {"key": "_rid", "type": "str"}, + "operation_type": {"key": "operationType", "type": "str"}, + "can_undelete": {"key": "canUndelete", "type": "str"}, + "can_undelete_reason": {"key": "canUndeleteReason", "type": "str"}, + "event_timestamp": {"key": "eventTimestamp", "type": "str"}, + "owner_id": {"key": "ownerId", "type": "str"}, + "owner_resource_id": {"key": "ownerResourceId", "type": "str"}, + "database": {"key": "database", "type": "RestorableSqlDatabasePropertiesResourceDatabase"}, + } + + def __init__( + self, *, database: Optional["_models.RestorableSqlDatabasePropertiesResourceDatabase"] = None, **kwargs: Any + ) -> None: + """ + :keyword database: Cosmos DB SQL database resource object. + :paramtype database: + ~azure.mgmt.cosmosdb.models.RestorableSqlDatabasePropertiesResourceDatabase + """ + super().__init__(**kwargs) + self.rid = None + self.operation_type = None + self.can_undelete = None + self.can_undelete_reason = None + self.event_timestamp = None + self.owner_id = None + self.owner_resource_id = None + self.database = database + + +class SqlDatabaseResource(_serialization.Model): + """Cosmos DB SQL database resource object. + + All required parameters must be populated in order to send to server. + + :ivar id: Name of the Cosmos DB SQL database. Required. + :vartype id: str + :ivar restore_parameters: Parameters to indicate the information about the restore. + :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" + and "Restore". + :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + """ + + _validation = { + "id": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, + "create_mode": {"key": "createMode", "type": "str"}, + } + + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, + create_mode: Union[str, "_models.CreateMode"] = "Default", + **kwargs: Any + ) -> None: + """ + :keyword id: Name of the Cosmos DB SQL database. Required. + :paramtype id: str + :keyword restore_parameters: Parameters to indicate the information about the restore. + :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: + "Default" and "Restore". + :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + """ + super().__init__(**kwargs) + self.id = id + self.restore_parameters = restore_parameters + self.create_mode = create_mode + + +class RestorableSqlDatabasePropertiesResourceDatabase( + SqlDatabaseResource, ExtendedResourceProperties +): # pylint: disable=name-too-long + """Cosmos DB SQL database resource object. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar rid: A system generated property. A unique identifier. + :vartype rid: str + :ivar ts: A system generated property that denotes the last updated timestamp of the resource. + :vartype ts: float + :ivar etag: A system generated property representing the resource etag required for optimistic + concurrency control. + :vartype etag: str + :ivar id: Name of the Cosmos DB SQL database. Required. + :vartype id: str + :ivar restore_parameters: Parameters to indicate the information about the restore. + :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" + and "Restore". + :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + :ivar colls: A system generated property that specified the addressable path of the collections + resource. + :vartype colls: str + :ivar users: A system generated property that specifies the addressable path of the users + resource. + :vartype users: str + :ivar self_property: A system generated property that specifies the addressable path of the + database resource. + :vartype self_property: str + """ + + _validation = { + "rid": {"readonly": True}, + "ts": {"readonly": True}, + "etag": {"readonly": True}, + "id": {"required": True}, + "colls": {"readonly": True}, + "users": {"readonly": True}, + "self_property": {"readonly": True}, + } + + _attribute_map = { + "rid": {"key": "_rid", "type": "str"}, + "ts": {"key": "_ts", "type": "float"}, + "etag": {"key": "_etag", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, + "create_mode": {"key": "createMode", "type": "str"}, + "colls": {"key": "_colls", "type": "str"}, + "users": {"key": "_users", "type": "str"}, + "self_property": {"key": "_self", "type": "str"}, + } + + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, + create_mode: Union[str, "_models.CreateMode"] = "Default", + **kwargs: Any + ) -> None: + """ + :keyword id: Name of the Cosmos DB SQL database. Required. + :paramtype id: str + :keyword restore_parameters: Parameters to indicate the information about the restore. + :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: + "Default" and "Restore". + :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + """ + super().__init__(id=id, restore_parameters=restore_parameters, create_mode=create_mode, **kwargs) + self.rid = None + self.ts = None + self.etag = None + self.colls = None + self.users = None + self.self_property = None + self.id = id + self.restore_parameters = restore_parameters + self.create_mode = create_mode + + +class RestorableSqlDatabasesListResult(_serialization.Model): + """The List operation response, that contains the SQL database events and their properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of SQL database events and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.RestorableSqlDatabaseGetResult] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[RestorableSqlDatabaseGetResult]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class RestorableSqlResourcesGetResult(_serialization.Model): + """Specific Databases to restore. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar database_name: The name of the database available for restore. + :vartype database_name: str + :ivar collection_names: The names of the collections available for restore. + :vartype collection_names: list[str] + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "database_name": {"key": "databaseName", "type": "str"}, + "collection_names": {"key": "collectionNames", "type": "[str]"}, + } + + def __init__( + self, *, database_name: Optional[str] = None, collection_names: Optional[List[str]] = None, **kwargs: Any + ) -> None: + """ + :keyword database_name: The name of the database available for restore. + :paramtype database_name: str + :keyword collection_names: The names of the collections available for restore. + :paramtype collection_names: list[str] + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.database_name = database_name + self.collection_names = collection_names + + +class RestorableSqlResourcesListResult(_serialization.Model): + """The List operation response, that contains the restorable SQL resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of restorable SQL resources, including the database and collection names. + :vartype value: list[~azure.mgmt.cosmosdb.models.RestorableSqlResourcesGetResult] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[RestorableSqlResourcesGetResult]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class RestorableTableGetResult(_serialization.Model): + """An Azure Cosmos DB Table event. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource Identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar resource: The resource of an Azure Cosmos DB Table event. + :vartype resource: ~azure.mgmt.cosmosdb.models.RestorableTablePropertiesResource + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "resource": {"key": "properties.resource", "type": "RestorableTablePropertiesResource"}, + } + + def __init__( + self, *, resource: Optional["_models.RestorableTablePropertiesResource"] = None, **kwargs: Any + ) -> None: + """ + :keyword resource: The resource of an Azure Cosmos DB Table event. + :paramtype resource: ~azure.mgmt.cosmosdb.models.RestorableTablePropertiesResource + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.resource = resource + + +class RestorableTablePropertiesResource(_serialization.Model): + """The resource of an Azure Cosmos DB Table event. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar rid: A system generated property. A unique identifier. + :vartype rid: str + :ivar operation_type: The operation type of this table event. Known values are: "Create", + "Replace", "Delete", "Recreate", and "SystemOperation". + :vartype operation_type: str or ~azure.mgmt.cosmosdb.models.OperationType + :ivar can_undelete: A state of this table to identify if this table is restorable in same + account. + :vartype can_undelete: str + :ivar can_undelete_reason: The reason why this table can not be restored in same account. + :vartype can_undelete_reason: str + :ivar event_timestamp: The time when this table event happened. + :vartype event_timestamp: str + :ivar owner_id: The name of this Table. + :vartype owner_id: str + :ivar owner_resource_id: The resource ID of this Table. + :vartype owner_resource_id: str + """ + + _validation = { + "rid": {"readonly": True}, + "operation_type": {"readonly": True}, + "can_undelete": {"readonly": True}, + "can_undelete_reason": {"readonly": True}, + "event_timestamp": {"readonly": True}, + "owner_id": {"readonly": True}, + "owner_resource_id": {"readonly": True}, + } + + _attribute_map = { + "rid": {"key": "_rid", "type": "str"}, + "operation_type": {"key": "operationType", "type": "str"}, + "can_undelete": {"key": "canUndelete", "type": "str"}, + "can_undelete_reason": {"key": "canUndeleteReason", "type": "str"}, + "event_timestamp": {"key": "eventTimestamp", "type": "str"}, + "owner_id": {"key": "ownerId", "type": "str"}, + "owner_resource_id": {"key": "ownerResourceId", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.rid = None + self.operation_type = None + self.can_undelete = None + self.can_undelete_reason = None + self.event_timestamp = None + self.owner_id = None + self.owner_resource_id = None + + +class RestorableTableResourcesGetResult(_serialization.Model): + """Specific Databases to restore. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the Table. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + + +class RestorableTableResourcesListResult(_serialization.Model): + """List of restorable table names. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of restorable table names. + :vartype value: list[~azure.mgmt.cosmosdb.models.RestorableTableResourcesGetResult] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[RestorableTableResourcesGetResult]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class RestorableTablesListResult(_serialization.Model): + """The List operation response, that contains the Table events and their properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of Table events and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.RestorableTableGetResult] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[RestorableTableGetResult]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class RestoreParameters(RestoreParametersBase): + """Parameters to indicate the information about the restore. + + :ivar restore_source: The id of the restorable database account from which the restore has to + be initiated. For example: + /subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{restorableDatabaseAccountName}. # pylint: disable=line-too-long + :vartype restore_source: str + :ivar restore_timestamp_in_utc: Time to which the account has to be restored (ISO-8601 format). + :vartype restore_timestamp_in_utc: ~datetime.datetime + :ivar restore_with_ttl_disabled: Specifies whether the restored account will have Time-To-Live + disabled upon the successful restore. + :vartype restore_with_ttl_disabled: bool + :ivar restore_mode: Describes the mode of the restore. "PointInTime" + :vartype restore_mode: str or ~azure.mgmt.cosmosdb.models.RestoreMode + :ivar databases_to_restore: List of specific databases available for restore. + :vartype databases_to_restore: list[~azure.mgmt.cosmosdb.models.DatabaseRestoreResource] + :ivar gremlin_databases_to_restore: List of specific gremlin databases available for restore. + :vartype gremlin_databases_to_restore: + list[~azure.mgmt.cosmosdb.models.GremlinDatabaseRestoreResource] + :ivar tables_to_restore: List of specific tables available for restore. + :vartype tables_to_restore: list[str] + :ivar source_backup_location: The source backup location for restore. + :vartype source_backup_location: str + """ + + _attribute_map = { + "restore_source": {"key": "restoreSource", "type": "str"}, + "restore_timestamp_in_utc": {"key": "restoreTimestampInUtc", "type": "iso-8601"}, + "restore_with_ttl_disabled": {"key": "restoreWithTtlDisabled", "type": "bool"}, + "restore_mode": {"key": "restoreMode", "type": "str"}, + "databases_to_restore": {"key": "databasesToRestore", "type": "[DatabaseRestoreResource]"}, + "gremlin_databases_to_restore": { + "key": "gremlinDatabasesToRestore", + "type": "[GremlinDatabaseRestoreResource]", + }, + "tables_to_restore": {"key": "tablesToRestore", "type": "[str]"}, + "source_backup_location": {"key": "sourceBackupLocation", "type": "str"}, + } + + def __init__( + self, + *, + restore_source: Optional[str] = None, + restore_timestamp_in_utc: Optional[datetime.datetime] = None, + restore_with_ttl_disabled: Optional[bool] = None, + restore_mode: Optional[Union[str, "_models.RestoreMode"]] = None, + databases_to_restore: Optional[List["_models.DatabaseRestoreResource"]] = None, + gremlin_databases_to_restore: Optional[List["_models.GremlinDatabaseRestoreResource"]] = None, + tables_to_restore: Optional[List[str]] = None, + source_backup_location: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword restore_source: The id of the restorable database account from which the restore has + to be initiated. For example: + /subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{restorableDatabaseAccountName}. # pylint: disable=line-too-long + :paramtype restore_source: str + :keyword restore_timestamp_in_utc: Time to which the account has to be restored (ISO-8601 + format). + :paramtype restore_timestamp_in_utc: ~datetime.datetime + :keyword restore_with_ttl_disabled: Specifies whether the restored account will have + Time-To-Live disabled upon the successful restore. + :paramtype restore_with_ttl_disabled: bool + :keyword restore_mode: Describes the mode of the restore. "PointInTime" + :paramtype restore_mode: str or ~azure.mgmt.cosmosdb.models.RestoreMode + :keyword databases_to_restore: List of specific databases available for restore. + :paramtype databases_to_restore: list[~azure.mgmt.cosmosdb.models.DatabaseRestoreResource] + :keyword gremlin_databases_to_restore: List of specific gremlin databases available for + restore. + :paramtype gremlin_databases_to_restore: + list[~azure.mgmt.cosmosdb.models.GremlinDatabaseRestoreResource] + :keyword tables_to_restore: List of specific tables available for restore. + :paramtype tables_to_restore: list[str] + :keyword source_backup_location: The source backup location for restore. + :paramtype source_backup_location: str + """ + super().__init__( + restore_source=restore_source, + restore_timestamp_in_utc=restore_timestamp_in_utc, + restore_with_ttl_disabled=restore_with_ttl_disabled, + **kwargs + ) + self.restore_mode = restore_mode + self.databases_to_restore = databases_to_restore + self.gremlin_databases_to_restore = gremlin_databases_to_restore + self.tables_to_restore = tables_to_restore + self.source_backup_location = source_backup_location + + +class RetrieveThroughputParameters(ARMResourceProperties): + """Cosmos DB retrieve throughput parameters object. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: The standard JSON format of a resource throughput. Required. + :vartype resource: ~azure.mgmt.cosmosdb.models.RetrieveThroughputPropertiesResource + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "resource": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "RetrieveThroughputPropertiesResource"}, + } + + def __init__( + self, + *, + resource: "_models.RetrieveThroughputPropertiesResource", + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: The standard JSON format of a resource throughput. Required. + :paramtype resource: ~azure.mgmt.cosmosdb.models.RetrieveThroughputPropertiesResource + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + + +class RetrieveThroughputPropertiesResource(_serialization.Model): + """Resource to retrieve throughput information for Cosmos DB resource. + + All required parameters must be populated in order to send to server. + + :ivar physical_partition_ids: Array of PhysicalPartitionId objects. Required. + :vartype physical_partition_ids: list[~azure.mgmt.cosmosdb.models.PhysicalPartitionId] + """ + + _validation = { + "physical_partition_ids": {"required": True}, + } + + _attribute_map = { + "physical_partition_ids": {"key": "physicalPartitionIds", "type": "[PhysicalPartitionId]"}, + } + + def __init__(self, *, physical_partition_ids: List["_models.PhysicalPartitionId"], **kwargs: Any) -> None: + """ + :keyword physical_partition_ids: Array of PhysicalPartitionId objects. Required. + :paramtype physical_partition_ids: list[~azure.mgmt.cosmosdb.models.PhysicalPartitionId] + """ + super().__init__(**kwargs) + self.physical_partition_ids = physical_partition_ids + + +class Role(_serialization.Model): + """The set of roles permitted through this Role Definition. + + :ivar db: The database name the role is applied. + :vartype db: str + :ivar role: The role name. + :vartype role: str + """ + + _attribute_map = { + "db": {"key": "db", "type": "str"}, + "role": {"key": "role", "type": "str"}, + } + + def __init__(self, *, db: Optional[str] = None, role: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword db: The database name the role is applied. + :paramtype db: str + :keyword role: The role name. + :paramtype role: str + """ + super().__init__(**kwargs) + self.db = db + self.role = role + + +class SeedNode(_serialization.Model): + """SeedNode. + + :ivar ip_address: IP address of this seed node. + :vartype ip_address: str + """ + + _attribute_map = { + "ip_address": {"key": "ipAddress", "type": "str"}, + } + + def __init__(self, *, ip_address: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword ip_address: IP address of this seed node. + :paramtype ip_address: str + """ + super().__init__(**kwargs) + self.ip_address = ip_address + + +class ServiceResource(ARMProxyResource): + """Properties for the database account. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the database account. + :vartype id: str + :ivar name: The name of the database account. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar properties: Services response resource. + :vartype properties: ~azure.mgmt.cosmosdb.models.ServiceResourceProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "properties": {"key": "properties", "type": "ServiceResourceProperties"}, + } + + def __init__(self, *, properties: Optional["_models.ServiceResourceProperties"] = None, **kwargs: Any) -> None: + """ + :keyword properties: Services response resource. + :paramtype properties: ~azure.mgmt.cosmosdb.models.ServiceResourceProperties + """ + super().__init__(**kwargs) + self.properties = properties + + +class ServiceResourceCreateUpdateParameters(_serialization.Model): + """Parameters for Create or Update request for ServiceResource. + + :ivar properties: Properties in ServiceResourceCreateUpdateParameters. + :vartype properties: ~azure.mgmt.cosmosdb.models.ServiceResourceCreateUpdateProperties + """ + + _attribute_map = { + "properties": {"key": "properties", "type": "ServiceResourceCreateUpdateProperties"}, + } + + def __init__( + self, *, properties: Optional["_models.ServiceResourceCreateUpdateProperties"] = None, **kwargs: Any + ) -> None: + """ + :keyword properties: Properties in ServiceResourceCreateUpdateParameters. + :paramtype properties: ~azure.mgmt.cosmosdb.models.ServiceResourceCreateUpdateProperties + """ + super().__init__(**kwargs) + self.properties = properties + + +class ServiceResourceListResult(_serialization.Model): + """The List operation response, that contains the Service Resource and their properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of Service Resource and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.ServiceResource] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[ServiceResource]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class SpatialSpec(_serialization.Model): + """SpatialSpec. + + :ivar path: The path for which the indexing behavior applies to. Index paths typically start + with root and end with wildcard (/path/*). + :vartype path: str + :ivar types: List of path's spatial type. + :vartype types: list[str or ~azure.mgmt.cosmosdb.models.SpatialType] + """ + + _attribute_map = { + "path": {"key": "path", "type": "str"}, + "types": {"key": "types", "type": "[str]"}, + } + + def __init__( + self, + *, + path: Optional[str] = None, + types: Optional[List[Union[str, "_models.SpatialType"]]] = None, + **kwargs: Any + ) -> None: + """ + :keyword path: The path for which the indexing behavior applies to. Index paths typically start + with root and end with wildcard (/path/*). + :paramtype path: str + :keyword types: List of path's spatial type. + :paramtype types: list[str or ~azure.mgmt.cosmosdb.models.SpatialType] + """ + super().__init__(**kwargs) + self.path = path + self.types = types + + +class SqlContainerCreateUpdateParameters(ARMResourceProperties): + """Parameters to create and update Cosmos DB container. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: The standard JSON format of a container. Required. + :vartype resource: ~azure.mgmt.cosmosdb.models.SqlContainerResource + :ivar options: A key-value pair of options to be applied for the request. This corresponds to + the headers sent with the request. + :vartype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "resource": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "SqlContainerResource"}, + "options": {"key": "properties.options", "type": "CreateUpdateOptions"}, + } + + def __init__( + self, + *, + resource: "_models.SqlContainerResource", + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + options: Optional["_models.CreateUpdateOptions"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: The standard JSON format of a container. Required. + :paramtype resource: ~azure.mgmt.cosmosdb.models.SqlContainerResource + :keyword options: A key-value pair of options to be applied for the request. This corresponds + to the headers sent with the request. + :paramtype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + self.options = options + + +class SqlContainerGetPropertiesOptions(OptionsResource): + """SqlContainerGetPropertiesOptions. + + :ivar throughput: Value of the Cosmos DB resource throughput or autoscaleSettings. Use the + ThroughputSetting resource when retrieving offer details. + :vartype throughput: int + :ivar autoscale_settings: Specifies the Autoscale settings. + :vartype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettings + """ + + +class SqlContainerGetPropertiesResource( + SqlContainerResource, ExtendedResourceProperties +): # pylint: disable=too-many-instance-attributes + """SqlContainerGetPropertiesResource. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar rid: A system generated property. A unique identifier. + :vartype rid: str + :ivar ts: A system generated property that denotes the last updated timestamp of the resource. + :vartype ts: float + :ivar etag: A system generated property representing the resource etag required for optimistic + concurrency control. + :vartype etag: str + :ivar id: Name of the Cosmos DB SQL container. Required. + :vartype id: str + :ivar indexing_policy: The configuration of the indexing policy. By default, the indexing is + automatic for all document paths within the container. + :vartype indexing_policy: ~azure.mgmt.cosmosdb.models.IndexingPolicy + :ivar partition_key: The configuration of the partition key to be used for partitioning data + into multiple partitions. + :vartype partition_key: ~azure.mgmt.cosmosdb.models.ContainerPartitionKey + :ivar default_ttl: Default time to live. + :vartype default_ttl: int + :ivar unique_key_policy: The unique key policy configuration for specifying uniqueness + constraints on documents in the collection in the Azure Cosmos DB service. + :vartype unique_key_policy: ~azure.mgmt.cosmosdb.models.UniqueKeyPolicy + :ivar conflict_resolution_policy: The conflict resolution policy for the container. + :vartype conflict_resolution_policy: ~azure.mgmt.cosmosdb.models.ConflictResolutionPolicy + :ivar client_encryption_policy: The client encryption policy for the container. + :vartype client_encryption_policy: ~azure.mgmt.cosmosdb.models.ClientEncryptionPolicy + :ivar analytical_storage_ttl: Analytical TTL. + :vartype analytical_storage_ttl: int + :ivar restore_parameters: Parameters to indicate the information about the restore. + :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" + and "Restore". + :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + :ivar materialized_view_definition: The configuration for defining Materialized Views. This + must be specified only for creating a Materialized View container. + :vartype materialized_view_definition: ~azure.mgmt.cosmosdb.models.MaterializedViewDefinition + :ivar computed_properties: List of computed properties. + :vartype computed_properties: list[~azure.mgmt.cosmosdb.models.ComputedProperty] + """ + + _validation = { + "rid": {"readonly": True}, + "ts": {"readonly": True}, + "etag": {"readonly": True}, + "id": {"required": True}, + } + + _attribute_map = { + "rid": {"key": "_rid", "type": "str"}, + "ts": {"key": "_ts", "type": "float"}, + "etag": {"key": "_etag", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "indexing_policy": {"key": "indexingPolicy", "type": "IndexingPolicy"}, + "partition_key": {"key": "partitionKey", "type": "ContainerPartitionKey"}, + "default_ttl": {"key": "defaultTtl", "type": "int"}, + "unique_key_policy": {"key": "uniqueKeyPolicy", "type": "UniqueKeyPolicy"}, + "conflict_resolution_policy": {"key": "conflictResolutionPolicy", "type": "ConflictResolutionPolicy"}, + "client_encryption_policy": {"key": "clientEncryptionPolicy", "type": "ClientEncryptionPolicy"}, + "analytical_storage_ttl": {"key": "analyticalStorageTtl", "type": "int"}, + "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, + "create_mode": {"key": "createMode", "type": "str"}, + "materialized_view_definition": {"key": "materializedViewDefinition", "type": "MaterializedViewDefinition"}, + "computed_properties": {"key": "computedProperties", "type": "[ComputedProperty]"}, + } + + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + indexing_policy: Optional["_models.IndexingPolicy"] = None, + partition_key: Optional["_models.ContainerPartitionKey"] = None, + default_ttl: Optional[int] = None, + unique_key_policy: Optional["_models.UniqueKeyPolicy"] = None, + conflict_resolution_policy: Optional["_models.ConflictResolutionPolicy"] = None, + client_encryption_policy: Optional["_models.ClientEncryptionPolicy"] = None, + analytical_storage_ttl: Optional[int] = None, + restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, + create_mode: Union[str, "_models.CreateMode"] = "Default", + materialized_view_definition: Optional["_models.MaterializedViewDefinition"] = None, + computed_properties: Optional[List["_models.ComputedProperty"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword id: Name of the Cosmos DB SQL container. Required. + :paramtype id: str + :keyword indexing_policy: The configuration of the indexing policy. By default, the indexing is + automatic for all document paths within the container. + :paramtype indexing_policy: ~azure.mgmt.cosmosdb.models.IndexingPolicy + :keyword partition_key: The configuration of the partition key to be used for partitioning data + into multiple partitions. + :paramtype partition_key: ~azure.mgmt.cosmosdb.models.ContainerPartitionKey + :keyword default_ttl: Default time to live. + :paramtype default_ttl: int + :keyword unique_key_policy: The unique key policy configuration for specifying uniqueness + constraints on documents in the collection in the Azure Cosmos DB service. + :paramtype unique_key_policy: ~azure.mgmt.cosmosdb.models.UniqueKeyPolicy + :keyword conflict_resolution_policy: The conflict resolution policy for the container. + :paramtype conflict_resolution_policy: ~azure.mgmt.cosmosdb.models.ConflictResolutionPolicy + :keyword client_encryption_policy: The client encryption policy for the container. + :paramtype client_encryption_policy: ~azure.mgmt.cosmosdb.models.ClientEncryptionPolicy + :keyword analytical_storage_ttl: Analytical TTL. + :paramtype analytical_storage_ttl: int + :keyword restore_parameters: Parameters to indicate the information about the restore. + :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: + "Default" and "Restore". + :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + :keyword materialized_view_definition: The configuration for defining Materialized Views. This + must be specified only for creating a Materialized View container. + :paramtype materialized_view_definition: ~azure.mgmt.cosmosdb.models.MaterializedViewDefinition + :keyword computed_properties: List of computed properties. + :paramtype computed_properties: list[~azure.mgmt.cosmosdb.models.ComputedProperty] + """ + super().__init__( + id=id, + indexing_policy=indexing_policy, + partition_key=partition_key, + default_ttl=default_ttl, + unique_key_policy=unique_key_policy, + conflict_resolution_policy=conflict_resolution_policy, + client_encryption_policy=client_encryption_policy, + analytical_storage_ttl=analytical_storage_ttl, + restore_parameters=restore_parameters, + create_mode=create_mode, + materialized_view_definition=materialized_view_definition, + computed_properties=computed_properties, + **kwargs + ) + self.rid = None + self.ts = None + self.etag = None + self.id = id + self.indexing_policy = indexing_policy + self.partition_key = partition_key + self.default_ttl = default_ttl + self.unique_key_policy = unique_key_policy + self.conflict_resolution_policy = conflict_resolution_policy + self.client_encryption_policy = client_encryption_policy + self.analytical_storage_ttl = analytical_storage_ttl + self.restore_parameters = restore_parameters + self.create_mode = create_mode + self.materialized_view_definition = materialized_view_definition + self.computed_properties = computed_properties + + +class SqlContainerGetResults(ARMResourceProperties): + """An Azure Cosmos DB container. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: + :vartype resource: ~azure.mgmt.cosmosdb.models.SqlContainerGetPropertiesResource + :ivar options: + :vartype options: ~azure.mgmt.cosmosdb.models.SqlContainerGetPropertiesOptions + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "SqlContainerGetPropertiesResource"}, + "options": {"key": "properties.options", "type": "SqlContainerGetPropertiesOptions"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + resource: Optional["_models.SqlContainerGetPropertiesResource"] = None, + options: Optional["_models.SqlContainerGetPropertiesOptions"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: + :paramtype resource: ~azure.mgmt.cosmosdb.models.SqlContainerGetPropertiesResource + :keyword options: + :paramtype options: ~azure.mgmt.cosmosdb.models.SqlContainerGetPropertiesOptions + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + self.options = options + + +class SqlContainerListResult(_serialization.Model): + """The List operation response, that contains the containers and their properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of containers and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.SqlContainerGetResults] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[SqlContainerGetResults]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class SqlDatabaseCreateUpdateParameters(ARMResourceProperties): + """Parameters to create and update Cosmos DB SQL database. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: The standard JSON format of a SQL database. Required. + :vartype resource: ~azure.mgmt.cosmosdb.models.SqlDatabaseResource + :ivar options: A key-value pair of options to be applied for the request. This corresponds to + the headers sent with the request. + :vartype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "resource": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "SqlDatabaseResource"}, + "options": {"key": "properties.options", "type": "CreateUpdateOptions"}, + } + + def __init__( + self, + *, + resource: "_models.SqlDatabaseResource", + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + options: Optional["_models.CreateUpdateOptions"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: The standard JSON format of a SQL database. Required. + :paramtype resource: ~azure.mgmt.cosmosdb.models.SqlDatabaseResource + :keyword options: A key-value pair of options to be applied for the request. This corresponds + to the headers sent with the request. + :paramtype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + self.options = options + + +class SqlDatabaseGetPropertiesOptions(OptionsResource): + """SqlDatabaseGetPropertiesOptions. + + :ivar throughput: Value of the Cosmos DB resource throughput or autoscaleSettings. Use the + ThroughputSetting resource when retrieving offer details. + :vartype throughput: int + :ivar autoscale_settings: Specifies the Autoscale settings. + :vartype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettings + """ + + +class SqlDatabaseGetPropertiesResource(SqlDatabaseResource, ExtendedResourceProperties): + """SqlDatabaseGetPropertiesResource. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar rid: A system generated property. A unique identifier. + :vartype rid: str + :ivar ts: A system generated property that denotes the last updated timestamp of the resource. + :vartype ts: float + :ivar etag: A system generated property representing the resource etag required for optimistic + concurrency control. + :vartype etag: str + :ivar id: Name of the Cosmos DB SQL database. Required. + :vartype id: str + :ivar restore_parameters: Parameters to indicate the information about the restore. + :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" + and "Restore". + :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + :ivar colls: A system generated property that specified the addressable path of the collections + resource. + :vartype colls: str + :ivar users: A system generated property that specifies the addressable path of the users + resource. + :vartype users: str + """ + + _validation = { + "rid": {"readonly": True}, + "ts": {"readonly": True}, + "etag": {"readonly": True}, + "id": {"required": True}, + } + + _attribute_map = { + "rid": {"key": "_rid", "type": "str"}, + "ts": {"key": "_ts", "type": "float"}, + "etag": {"key": "_etag", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, + "create_mode": {"key": "createMode", "type": "str"}, + "colls": {"key": "_colls", "type": "str"}, + "users": {"key": "_users", "type": "str"}, + } + + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, + create_mode: Union[str, "_models.CreateMode"] = "Default", + colls: Optional[str] = None, + users: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword id: Name of the Cosmos DB SQL database. Required. + :paramtype id: str + :keyword restore_parameters: Parameters to indicate the information about the restore. + :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: + "Default" and "Restore". + :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + :keyword colls: A system generated property that specified the addressable path of the + collections resource. + :paramtype colls: str + :keyword users: A system generated property that specifies the addressable path of the users + resource. + :paramtype users: str + """ + super().__init__(id=id, restore_parameters=restore_parameters, create_mode=create_mode, **kwargs) + self.rid = None + self.ts = None + self.etag = None + self.colls = colls + self.users = users + self.id = id + self.restore_parameters = restore_parameters + self.create_mode = create_mode + + +class SqlDatabaseGetResults(ARMResourceProperties): + """An Azure Cosmos DB SQL database. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: + :vartype resource: ~azure.mgmt.cosmosdb.models.SqlDatabaseGetPropertiesResource + :ivar options: + :vartype options: ~azure.mgmt.cosmosdb.models.SqlDatabaseGetPropertiesOptions + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "SqlDatabaseGetPropertiesResource"}, + "options": {"key": "properties.options", "type": "SqlDatabaseGetPropertiesOptions"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + resource: Optional["_models.SqlDatabaseGetPropertiesResource"] = None, + options: Optional["_models.SqlDatabaseGetPropertiesOptions"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: + :paramtype resource: ~azure.mgmt.cosmosdb.models.SqlDatabaseGetPropertiesResource + :keyword options: + :paramtype options: ~azure.mgmt.cosmosdb.models.SqlDatabaseGetPropertiesOptions + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + self.options = options + + +class SqlDatabaseListResult(_serialization.Model): + """The List operation response, that contains the SQL databases and their properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of SQL databases and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.SqlDatabaseGetResults] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[SqlDatabaseGetResults]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class SqlDedicatedGatewayRegionalServiceResource(RegionalServiceResource): # pylint: disable=name-too-long + """Resource for a regional service location. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: The regional service name. + :vartype name: str + :ivar location: The location name. + :vartype location: str + :ivar status: Describes the status of a service. Known values are: "Creating", "Running", + "Updating", "Deleting", "Error", and "Stopped". + :vartype status: str or ~azure.mgmt.cosmosdb.models.ServiceStatus + :ivar sql_dedicated_gateway_endpoint: The regional endpoint for SqlDedicatedGateway. + :vartype sql_dedicated_gateway_endpoint: str + """ + + _validation = { + "name": {"readonly": True}, + "location": {"readonly": True}, + "status": {"readonly": True}, + "sql_dedicated_gateway_endpoint": {"readonly": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "sql_dedicated_gateway_endpoint": {"key": "sqlDedicatedGatewayEndpoint", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.sql_dedicated_gateway_endpoint = None + + +class SqlDedicatedGatewayServiceResource(_serialization.Model): + """Describes the service response property for SqlDedicatedGateway. + + :ivar properties: Properties for SqlDedicatedGatewayServiceResource. + :vartype properties: ~azure.mgmt.cosmosdb.models.SqlDedicatedGatewayServiceResourceProperties + """ + + _attribute_map = { + "properties": {"key": "properties", "type": "SqlDedicatedGatewayServiceResourceProperties"}, + } + + def __init__( + self, *, properties: Optional["_models.SqlDedicatedGatewayServiceResourceProperties"] = None, **kwargs: Any + ) -> None: + """ + :keyword properties: Properties for SqlDedicatedGatewayServiceResource. + :paramtype properties: ~azure.mgmt.cosmosdb.models.SqlDedicatedGatewayServiceResourceProperties + """ + super().__init__(**kwargs) + self.properties = properties + + +class SqlDedicatedGatewayServiceResourceCreateUpdateProperties( + ServiceResourceCreateUpdateProperties +): # pylint: disable=name-too-long + """Properties for Create or Update request for SqlDedicatedGatewayServiceResource. + + All required parameters must be populated in order to send to server. + + :ivar instance_size: Instance type for the service. Known values are: "Cosmos.D4s", + "Cosmos.D8s", and "Cosmos.D16s". + :vartype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize + :ivar instance_count: Instance count for the service. + :vartype instance_count: int + :ivar service_type: ServiceType for the service. Required. Known values are: + "SqlDedicatedGateway", "DataTransfer", "GraphAPICompute", and "MaterializedViewsBuilder". + :vartype service_type: str or ~azure.mgmt.cosmosdb.models.ServiceType + :ivar dedicated_gateway_type: DedicatedGatewayType for the service. Known values are: + "IntegratedCache" and "DistributedQuery". + :vartype dedicated_gateway_type: str or ~azure.mgmt.cosmosdb.models.DedicatedGatewayType + """ + + _validation = { + "instance_count": {"minimum": 0}, + "service_type": {"required": True}, + } + + _attribute_map = { + "instance_size": {"key": "instanceSize", "type": "str"}, + "instance_count": {"key": "instanceCount", "type": "int"}, + "service_type": {"key": "serviceType", "type": "str"}, + "dedicated_gateway_type": {"key": "dedicatedGatewayType", "type": "str"}, + } + + def __init__( + self, + *, + instance_size: Optional[Union[str, "_models.ServiceSize"]] = None, + instance_count: Optional[int] = None, + dedicated_gateway_type: Optional[Union[str, "_models.DedicatedGatewayType"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword instance_size: Instance type for the service. Known values are: "Cosmos.D4s", + "Cosmos.D8s", and "Cosmos.D16s". + :paramtype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize + :keyword instance_count: Instance count for the service. + :paramtype instance_count: int + :keyword dedicated_gateway_type: DedicatedGatewayType for the service. Known values are: + "IntegratedCache" and "DistributedQuery". + :paramtype dedicated_gateway_type: str or ~azure.mgmt.cosmosdb.models.DedicatedGatewayType + """ + super().__init__(instance_size=instance_size, instance_count=instance_count, **kwargs) + self.service_type: str = "SqlDedicatedGateway" + self.dedicated_gateway_type = dedicated_gateway_type + + +class SqlDedicatedGatewayServiceResourceProperties(ServiceResourceProperties): # pylint: disable=name-too-long + """Properties for SqlDedicatedGatewayServiceResource. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar additional_properties: Unmatched properties from the message are deserialized to this + collection. + :vartype additional_properties: dict[str, any] + :ivar creation_time: Time of the last state change (ISO-8601 format). + :vartype creation_time: ~datetime.datetime + :ivar instance_size: Instance type for the service. Known values are: "Cosmos.D4s", + "Cosmos.D8s", and "Cosmos.D16s". + :vartype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize + :ivar instance_count: Instance count for the service. + :vartype instance_count: int + :ivar service_type: ServiceType for the service. Required. Known values are: + "SqlDedicatedGateway", "DataTransfer", "GraphAPICompute", and "MaterializedViewsBuilder". + :vartype service_type: str or ~azure.mgmt.cosmosdb.models.ServiceType + :ivar status: Describes the status of a service. Known values are: "Creating", "Running", + "Updating", "Deleting", "Error", and "Stopped". + :vartype status: str or ~azure.mgmt.cosmosdb.models.ServiceStatus + :ivar sql_dedicated_gateway_endpoint: SqlDedicatedGateway endpoint for the service. + :vartype sql_dedicated_gateway_endpoint: str + :ivar dedicated_gateway_type: DedicatedGatewayType for the service. Known values are: + "IntegratedCache" and "DistributedQuery". + :vartype dedicated_gateway_type: str or ~azure.mgmt.cosmosdb.models.DedicatedGatewayType + :ivar locations: An array that contains all of the locations for the service. + :vartype locations: + list[~azure.mgmt.cosmosdb.models.SqlDedicatedGatewayRegionalServiceResource] + """ + + _validation = { + "creation_time": {"readonly": True}, + "instance_count": {"minimum": 0}, + "service_type": {"required": True}, + "status": {"readonly": True}, + "locations": {"readonly": True}, + } + + _attribute_map = { + "additional_properties": {"key": "", "type": "{object}"}, + "creation_time": {"key": "creationTime", "type": "iso-8601"}, + "instance_size": {"key": "instanceSize", "type": "str"}, + "instance_count": {"key": "instanceCount", "type": "int"}, + "service_type": {"key": "serviceType", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "sql_dedicated_gateway_endpoint": {"key": "sqlDedicatedGatewayEndpoint", "type": "str"}, + "dedicated_gateway_type": {"key": "dedicatedGatewayType", "type": "str"}, + "locations": {"key": "locations", "type": "[SqlDedicatedGatewayRegionalServiceResource]"}, + } + + def __init__( + self, + *, + additional_properties: Optional[Dict[str, Any]] = None, + instance_size: Optional[Union[str, "_models.ServiceSize"]] = None, + instance_count: Optional[int] = None, + sql_dedicated_gateway_endpoint: Optional[str] = None, + dedicated_gateway_type: Optional[Union[str, "_models.DedicatedGatewayType"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword additional_properties: Unmatched properties from the message are deserialized to this + collection. + :paramtype additional_properties: dict[str, any] + :keyword instance_size: Instance type for the service. Known values are: "Cosmos.D4s", + "Cosmos.D8s", and "Cosmos.D16s". + :paramtype instance_size: str or ~azure.mgmt.cosmosdb.models.ServiceSize + :keyword instance_count: Instance count for the service. + :paramtype instance_count: int + :keyword sql_dedicated_gateway_endpoint: SqlDedicatedGateway endpoint for the service. + :paramtype sql_dedicated_gateway_endpoint: str + :keyword dedicated_gateway_type: DedicatedGatewayType for the service. Known values are: + "IntegratedCache" and "DistributedQuery". + :paramtype dedicated_gateway_type: str or ~azure.mgmt.cosmosdb.models.DedicatedGatewayType + """ + super().__init__( + additional_properties=additional_properties, + instance_size=instance_size, + instance_count=instance_count, + **kwargs + ) + self.service_type: str = "SqlDedicatedGateway" + self.sql_dedicated_gateway_endpoint = sql_dedicated_gateway_endpoint + self.dedicated_gateway_type = dedicated_gateway_type + self.locations = None + + +class SqlRoleAssignmentCreateUpdateParameters(_serialization.Model): + """Parameters to create and update an Azure Cosmos DB SQL Role Assignment. + + :ivar role_definition_id: The unique identifier for the associated Role Definition. + :vartype role_definition_id: str + :ivar scope: The data plane resource path for which access is being granted through this Role + Assignment. + :vartype scope: str + :ivar principal_id: The unique identifier for the associated AAD principal in the AAD graph to + which access is being granted through this Role Assignment. Tenant ID for the principal is + inferred using the tenant associated with the subscription. + :vartype principal_id: str + """ + + _attribute_map = { + "role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "principal_id": {"key": "properties.principalId", "type": "str"}, + } + + def __init__( + self, + *, + role_definition_id: Optional[str] = None, + scope: Optional[str] = None, + principal_id: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword role_definition_id: The unique identifier for the associated Role Definition. + :paramtype role_definition_id: str + :keyword scope: The data plane resource path for which access is being granted through this + Role Assignment. + :paramtype scope: str + :keyword principal_id: The unique identifier for the associated AAD principal in the AAD graph + to which access is being granted through this Role Assignment. Tenant ID for the principal is + inferred using the tenant associated with the subscription. + :paramtype principal_id: str + """ + super().__init__(**kwargs) + self.role_definition_id = role_definition_id + self.scope = scope + self.principal_id = principal_id + + +class SqlRoleAssignmentGetResults(ARMProxyResource): + """An Azure Cosmos DB Role Assignment. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the database account. + :vartype id: str + :ivar name: The name of the database account. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar role_definition_id: The unique identifier for the associated Role Definition. + :vartype role_definition_id: str + :ivar scope: The data plane resource path for which access is being granted through this Role + Assignment. + :vartype scope: str + :ivar principal_id: The unique identifier for the associated AAD principal in the AAD graph to + which access is being granted through this Role Assignment. Tenant ID for the principal is + inferred using the tenant associated with the subscription. + :vartype principal_id: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "principal_id": {"key": "properties.principalId", "type": "str"}, + } + + def __init__( + self, + *, + role_definition_id: Optional[str] = None, + scope: Optional[str] = None, + principal_id: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword role_definition_id: The unique identifier for the associated Role Definition. + :paramtype role_definition_id: str + :keyword scope: The data plane resource path for which access is being granted through this + Role Assignment. + :paramtype scope: str + :keyword principal_id: The unique identifier for the associated AAD principal in the AAD graph + to which access is being granted through this Role Assignment. Tenant ID for the principal is + inferred using the tenant associated with the subscription. + :paramtype principal_id: str + """ + super().__init__(**kwargs) + self.role_definition_id = role_definition_id + self.scope = scope + self.principal_id = principal_id + + +class SqlRoleAssignmentListResult(_serialization.Model): + """The relevant Role Assignments. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of Role Assignments and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.SqlRoleAssignmentGetResults] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[SqlRoleAssignmentGetResults]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class SqlRoleDefinitionCreateUpdateParameters(_serialization.Model): + """Parameters to create and update an Azure Cosmos DB SQL Role Definition. + + :ivar role_name: A user-friendly name for the Role Definition. Must be unique for the database + account. + :vartype role_name: str + :ivar type: Indicates whether the Role Definition was built-in or user created. Known values + are: "BuiltInRole" and "CustomRole". + :vartype type: str or ~azure.mgmt.cosmosdb.models.RoleDefinitionType + :ivar assignable_scopes: A set of fully qualified Scopes at or below which Role Assignments may + be created using this Role Definition. This will allow application of this Role Definition on + the entire database account or any underlying Database / Collection. Must have at least one + element. Scopes higher than Database account are not enforceable as assignable Scopes. Note + that resources referenced in assignable Scopes need not exist. + :vartype assignable_scopes: list[str] + :ivar permissions: The set of operations allowed through this Role Definition. + :vartype permissions: list[~azure.mgmt.cosmosdb.models.Permission] + """ + + _attribute_map = { + "role_name": {"key": "properties.roleName", "type": "str"}, + "type": {"key": "properties.type", "type": "str"}, + "assignable_scopes": {"key": "properties.assignableScopes", "type": "[str]"}, + "permissions": {"key": "properties.permissions", "type": "[Permission]"}, + } + + def __init__( + self, + *, + role_name: Optional[str] = None, + type: Optional[Union[str, "_models.RoleDefinitionType"]] = None, + assignable_scopes: Optional[List[str]] = None, + permissions: Optional[List["_models.Permission"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword role_name: A user-friendly name for the Role Definition. Must be unique for the + database account. + :paramtype role_name: str + :keyword type: Indicates whether the Role Definition was built-in or user created. Known values + are: "BuiltInRole" and "CustomRole". + :paramtype type: str or ~azure.mgmt.cosmosdb.models.RoleDefinitionType + :keyword assignable_scopes: A set of fully qualified Scopes at or below which Role Assignments + may be created using this Role Definition. This will allow application of this Role Definition + on the entire database account or any underlying Database / Collection. Must have at least one + element. Scopes higher than Database account are not enforceable as assignable Scopes. Note + that resources referenced in assignable Scopes need not exist. + :paramtype assignable_scopes: list[str] + :keyword permissions: The set of operations allowed through this Role Definition. + :paramtype permissions: list[~azure.mgmt.cosmosdb.models.Permission] + """ + super().__init__(**kwargs) + self.role_name = role_name + self.type = type + self.assignable_scopes = assignable_scopes + self.permissions = permissions + + +class SqlRoleDefinitionGetResults(ARMProxyResource): + """An Azure Cosmos DB SQL Role Definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the database account. + :vartype id: str + :ivar name: The name of the database account. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar role_name: A user-friendly name for the Role Definition. Must be unique for the database + account. + :vartype role_name: str + :ivar type_properties_type: Indicates whether the Role Definition was built-in or user created. + Known values are: "BuiltInRole" and "CustomRole". + :vartype type_properties_type: str or ~azure.mgmt.cosmosdb.models.RoleDefinitionType + :ivar assignable_scopes: A set of fully qualified Scopes at or below which Role Assignments may + be created using this Role Definition. This will allow application of this Role Definition on + the entire database account or any underlying Database / Collection. Must have at least one + element. Scopes higher than Database account are not enforceable as assignable Scopes. Note + that resources referenced in assignable Scopes need not exist. + :vartype assignable_scopes: list[str] + :ivar permissions: The set of operations allowed through this Role Definition. + :vartype permissions: list[~azure.mgmt.cosmosdb.models.Permission] + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "role_name": {"key": "properties.roleName", "type": "str"}, + "type_properties_type": {"key": "properties.type", "type": "str"}, + "assignable_scopes": {"key": "properties.assignableScopes", "type": "[str]"}, + "permissions": {"key": "properties.permissions", "type": "[Permission]"}, + } + + def __init__( + self, + *, + role_name: Optional[str] = None, + type_properties_type: Optional[Union[str, "_models.RoleDefinitionType"]] = None, + assignable_scopes: Optional[List[str]] = None, + permissions: Optional[List["_models.Permission"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword role_name: A user-friendly name for the Role Definition. Must be unique for the + database account. + :paramtype role_name: str + :keyword type_properties_type: Indicates whether the Role Definition was built-in or user + created. Known values are: "BuiltInRole" and "CustomRole". + :paramtype type_properties_type: str or ~azure.mgmt.cosmosdb.models.RoleDefinitionType + :keyword assignable_scopes: A set of fully qualified Scopes at or below which Role Assignments + may be created using this Role Definition. This will allow application of this Role Definition + on the entire database account or any underlying Database / Collection. Must have at least one + element. Scopes higher than Database account are not enforceable as assignable Scopes. Note + that resources referenced in assignable Scopes need not exist. + :paramtype assignable_scopes: list[str] + :keyword permissions: The set of operations allowed through this Role Definition. + :paramtype permissions: list[~azure.mgmt.cosmosdb.models.Permission] + """ + super().__init__(**kwargs) + self.role_name = role_name + self.type_properties_type = type_properties_type + self.assignable_scopes = assignable_scopes + self.permissions = permissions + + +class SqlRoleDefinitionListResult(_serialization.Model): + """The relevant Role Definitions. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of Role Definitions and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.SqlRoleDefinitionGetResults] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[SqlRoleDefinitionGetResults]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class SqlStoredProcedureCreateUpdateParameters(ARMResourceProperties): + """Parameters to create and update Cosmos DB storedProcedure. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: The standard JSON format of a storedProcedure. Required. + :vartype resource: ~azure.mgmt.cosmosdb.models.SqlStoredProcedureResource + :ivar options: A key-value pair of options to be applied for the request. This corresponds to + the headers sent with the request. + :vartype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "resource": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "SqlStoredProcedureResource"}, + "options": {"key": "properties.options", "type": "CreateUpdateOptions"}, + } + + def __init__( + self, + *, + resource: "_models.SqlStoredProcedureResource", + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + options: Optional["_models.CreateUpdateOptions"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: The standard JSON format of a storedProcedure. Required. + :paramtype resource: ~azure.mgmt.cosmosdb.models.SqlStoredProcedureResource + :keyword options: A key-value pair of options to be applied for the request. This corresponds + to the headers sent with the request. + :paramtype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + self.options = options + + +class SqlStoredProcedureResource(_serialization.Model): + """Cosmos DB SQL storedProcedure resource object. + + All required parameters must be populated in order to send to server. + + :ivar id: Name of the Cosmos DB SQL storedProcedure. Required. + :vartype id: str + :ivar body: Body of the Stored Procedure. + :vartype body: str + """ + + _validation = { + "id": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "body": {"key": "body", "type": "str"}, + } + + def __init__( + self, *, id: str, body: Optional[str] = None, **kwargs: Any # pylint: disable=redefined-builtin + ) -> None: + """ + :keyword id: Name of the Cosmos DB SQL storedProcedure. Required. + :paramtype id: str + :keyword body: Body of the Stored Procedure. + :paramtype body: str + """ + super().__init__(**kwargs) + self.id = id + self.body = body + + +class SqlStoredProcedureGetPropertiesResource(SqlStoredProcedureResource, ExtendedResourceProperties): + """SqlStoredProcedureGetPropertiesResource. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar rid: A system generated property. A unique identifier. + :vartype rid: str + :ivar ts: A system generated property that denotes the last updated timestamp of the resource. + :vartype ts: float + :ivar etag: A system generated property representing the resource etag required for optimistic + concurrency control. + :vartype etag: str + :ivar id: Name of the Cosmos DB SQL storedProcedure. Required. + :vartype id: str + :ivar body: Body of the Stored Procedure. + :vartype body: str + """ + + _validation = { + "rid": {"readonly": True}, + "ts": {"readonly": True}, + "etag": {"readonly": True}, + "id": {"required": True}, + } + + _attribute_map = { + "rid": {"key": "_rid", "type": "str"}, + "ts": {"key": "_ts", "type": "float"}, + "etag": {"key": "_etag", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "body": {"key": "body", "type": "str"}, + } + + def __init__( + self, *, id: str, body: Optional[str] = None, **kwargs: Any # pylint: disable=redefined-builtin + ) -> None: + """ + :keyword id: Name of the Cosmos DB SQL storedProcedure. Required. + :paramtype id: str + :keyword body: Body of the Stored Procedure. + :paramtype body: str + """ + super().__init__(id=id, body=body, **kwargs) + self.rid = None + self.ts = None + self.etag = None + self.id = id + self.body = body + + +class SqlStoredProcedureGetResults(ARMResourceProperties): + """An Azure Cosmos DB storedProcedure. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: + :vartype resource: ~azure.mgmt.cosmosdb.models.SqlStoredProcedureGetPropertiesResource + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "SqlStoredProcedureGetPropertiesResource"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + resource: Optional["_models.SqlStoredProcedureGetPropertiesResource"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: + :paramtype resource: ~azure.mgmt.cosmosdb.models.SqlStoredProcedureGetPropertiesResource + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + + +class SqlStoredProcedureListResult(_serialization.Model): + """The List operation response, that contains the storedProcedures and their properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of storedProcedures and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.SqlStoredProcedureGetResults] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[SqlStoredProcedureGetResults]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class SqlTriggerCreateUpdateParameters(ARMResourceProperties): + """Parameters to create and update Cosmos DB trigger. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: The standard JSON format of a trigger. Required. + :vartype resource: ~azure.mgmt.cosmosdb.models.SqlTriggerResource + :ivar options: A key-value pair of options to be applied for the request. This corresponds to + the headers sent with the request. + :vartype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "resource": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "SqlTriggerResource"}, + "options": {"key": "properties.options", "type": "CreateUpdateOptions"}, + } + + def __init__( + self, + *, + resource: "_models.SqlTriggerResource", + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + options: Optional["_models.CreateUpdateOptions"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: The standard JSON format of a trigger. Required. + :paramtype resource: ~azure.mgmt.cosmosdb.models.SqlTriggerResource + :keyword options: A key-value pair of options to be applied for the request. This corresponds + to the headers sent with the request. + :paramtype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + self.options = options + + +class SqlTriggerResource(_serialization.Model): + """Cosmos DB SQL trigger resource object. + + All required parameters must be populated in order to send to server. + + :ivar id: Name of the Cosmos DB SQL trigger. Required. + :vartype id: str + :ivar body: Body of the Trigger. + :vartype body: str + :ivar trigger_type: Type of the Trigger. Known values are: "Pre" and "Post". + :vartype trigger_type: str or ~azure.mgmt.cosmosdb.models.TriggerType + :ivar trigger_operation: The operation the trigger is associated with. Known values are: "All", + "Create", "Update", "Delete", and "Replace". + :vartype trigger_operation: str or ~azure.mgmt.cosmosdb.models.TriggerOperation + """ + + _validation = { + "id": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "body": {"key": "body", "type": "str"}, + "trigger_type": {"key": "triggerType", "type": "str"}, + "trigger_operation": {"key": "triggerOperation", "type": "str"}, + } + + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + body: Optional[str] = None, + trigger_type: Optional[Union[str, "_models.TriggerType"]] = None, + trigger_operation: Optional[Union[str, "_models.TriggerOperation"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword id: Name of the Cosmos DB SQL trigger. Required. + :paramtype id: str + :keyword body: Body of the Trigger. + :paramtype body: str + :keyword trigger_type: Type of the Trigger. Known values are: "Pre" and "Post". + :paramtype trigger_type: str or ~azure.mgmt.cosmosdb.models.TriggerType + :keyword trigger_operation: The operation the trigger is associated with. Known values are: + "All", "Create", "Update", "Delete", and "Replace". + :paramtype trigger_operation: str or ~azure.mgmt.cosmosdb.models.TriggerOperation + """ + super().__init__(**kwargs) + self.id = id + self.body = body + self.trigger_type = trigger_type + self.trigger_operation = trigger_operation + + +class SqlTriggerGetPropertiesResource(SqlTriggerResource, ExtendedResourceProperties): + """SqlTriggerGetPropertiesResource. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar rid: A system generated property. A unique identifier. + :vartype rid: str + :ivar ts: A system generated property that denotes the last updated timestamp of the resource. + :vartype ts: float + :ivar etag: A system generated property representing the resource etag required for optimistic + concurrency control. + :vartype etag: str + :ivar id: Name of the Cosmos DB SQL trigger. Required. + :vartype id: str + :ivar body: Body of the Trigger. + :vartype body: str + :ivar trigger_type: Type of the Trigger. Known values are: "Pre" and "Post". + :vartype trigger_type: str or ~azure.mgmt.cosmosdb.models.TriggerType + :ivar trigger_operation: The operation the trigger is associated with. Known values are: "All", + "Create", "Update", "Delete", and "Replace". + :vartype trigger_operation: str or ~azure.mgmt.cosmosdb.models.TriggerOperation + """ + + _validation = { + "rid": {"readonly": True}, + "ts": {"readonly": True}, + "etag": {"readonly": True}, + "id": {"required": True}, + } + + _attribute_map = { + "rid": {"key": "_rid", "type": "str"}, + "ts": {"key": "_ts", "type": "float"}, + "etag": {"key": "_etag", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "body": {"key": "body", "type": "str"}, + "trigger_type": {"key": "triggerType", "type": "str"}, + "trigger_operation": {"key": "triggerOperation", "type": "str"}, + } + + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + body: Optional[str] = None, + trigger_type: Optional[Union[str, "_models.TriggerType"]] = None, + trigger_operation: Optional[Union[str, "_models.TriggerOperation"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword id: Name of the Cosmos DB SQL trigger. Required. + :paramtype id: str + :keyword body: Body of the Trigger. + :paramtype body: str + :keyword trigger_type: Type of the Trigger. Known values are: "Pre" and "Post". + :paramtype trigger_type: str or ~azure.mgmt.cosmosdb.models.TriggerType + :keyword trigger_operation: The operation the trigger is associated with. Known values are: + "All", "Create", "Update", "Delete", and "Replace". + :paramtype trigger_operation: str or ~azure.mgmt.cosmosdb.models.TriggerOperation + """ + super().__init__(id=id, body=body, trigger_type=trigger_type, trigger_operation=trigger_operation, **kwargs) + self.rid = None + self.ts = None + self.etag = None + self.id = id + self.body = body + self.trigger_type = trigger_type + self.trigger_operation = trigger_operation + + +class SqlTriggerGetResults(ARMResourceProperties): + """An Azure Cosmos DB trigger. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: + :vartype resource: ~azure.mgmt.cosmosdb.models.SqlTriggerGetPropertiesResource + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "SqlTriggerGetPropertiesResource"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + resource: Optional["_models.SqlTriggerGetPropertiesResource"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: + :paramtype resource: ~azure.mgmt.cosmosdb.models.SqlTriggerGetPropertiesResource + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + + +class SqlTriggerListResult(_serialization.Model): + """The List operation response, that contains the triggers and their properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of triggers and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.SqlTriggerGetResults] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[SqlTriggerGetResults]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class SqlUserDefinedFunctionCreateUpdateParameters(ARMResourceProperties): # pylint: disable=name-too-long + """Parameters to create and update Cosmos DB userDefinedFunction. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: The standard JSON format of a userDefinedFunction. Required. + :vartype resource: ~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionResource + :ivar options: A key-value pair of options to be applied for the request. This corresponds to + the headers sent with the request. + :vartype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "resource": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "SqlUserDefinedFunctionResource"}, + "options": {"key": "properties.options", "type": "CreateUpdateOptions"}, + } + + def __init__( + self, + *, + resource: "_models.SqlUserDefinedFunctionResource", + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + options: Optional["_models.CreateUpdateOptions"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: The standard JSON format of a userDefinedFunction. Required. + :paramtype resource: ~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionResource + :keyword options: A key-value pair of options to be applied for the request. This corresponds + to the headers sent with the request. + :paramtype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + self.options = options + + +class SqlUserDefinedFunctionResource(_serialization.Model): + """Cosmos DB SQL userDefinedFunction resource object. + + All required parameters must be populated in order to send to server. + + :ivar id: Name of the Cosmos DB SQL userDefinedFunction. Required. + :vartype id: str + :ivar body: Body of the User Defined Function. + :vartype body: str + """ + + _validation = { + "id": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "body": {"key": "body", "type": "str"}, + } + + def __init__( + self, *, id: str, body: Optional[str] = None, **kwargs: Any # pylint: disable=redefined-builtin + ) -> None: + """ + :keyword id: Name of the Cosmos DB SQL userDefinedFunction. Required. + :paramtype id: str + :keyword body: Body of the User Defined Function. + :paramtype body: str + """ + super().__init__(**kwargs) + self.id = id + self.body = body + + +class SqlUserDefinedFunctionGetPropertiesResource( + SqlUserDefinedFunctionResource, ExtendedResourceProperties +): # pylint: disable=name-too-long + """SqlUserDefinedFunctionGetPropertiesResource. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar rid: A system generated property. A unique identifier. + :vartype rid: str + :ivar ts: A system generated property that denotes the last updated timestamp of the resource. + :vartype ts: float + :ivar etag: A system generated property representing the resource etag required for optimistic + concurrency control. + :vartype etag: str + :ivar id: Name of the Cosmos DB SQL userDefinedFunction. Required. + :vartype id: str + :ivar body: Body of the User Defined Function. + :vartype body: str + """ + + _validation = { + "rid": {"readonly": True}, + "ts": {"readonly": True}, + "etag": {"readonly": True}, + "id": {"required": True}, + } + + _attribute_map = { + "rid": {"key": "_rid", "type": "str"}, + "ts": {"key": "_ts", "type": "float"}, + "etag": {"key": "_etag", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "body": {"key": "body", "type": "str"}, + } + + def __init__( + self, *, id: str, body: Optional[str] = None, **kwargs: Any # pylint: disable=redefined-builtin + ) -> None: + """ + :keyword id: Name of the Cosmos DB SQL userDefinedFunction. Required. + :paramtype id: str + :keyword body: Body of the User Defined Function. + :paramtype body: str + """ + super().__init__(id=id, body=body, **kwargs) + self.rid = None + self.ts = None + self.etag = None + self.id = id + self.body = body + + +class SqlUserDefinedFunctionGetResults(ARMResourceProperties): + """An Azure Cosmos DB userDefinedFunction. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: + :vartype resource: ~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionGetPropertiesResource + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "SqlUserDefinedFunctionGetPropertiesResource"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + resource: Optional["_models.SqlUserDefinedFunctionGetPropertiesResource"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: + :paramtype resource: ~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionGetPropertiesResource + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + + +class SqlUserDefinedFunctionListResult(_serialization.Model): + """The List operation response, that contains the userDefinedFunctions and their properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of userDefinedFunctions and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionGetResults] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[SqlUserDefinedFunctionGetResults]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class SystemData(_serialization.Model): + """Metadata pertaining to creation and last modification of the resource. + + :ivar created_by: The identity that created the resource. + :vartype created_by: str + :ivar created_by_type: The type of identity that created the resource. Known values are: + "User", "Application", "ManagedIdentity", and "Key". + :vartype created_by_type: str or ~azure.mgmt.cosmosdb.models.CreatedByType + :ivar created_at: The timestamp of resource creation (UTC). + :vartype created_at: ~datetime.datetime + :ivar last_modified_by: The identity that last modified the resource. + :vartype last_modified_by: str + :ivar last_modified_by_type: The type of identity that last modified the resource. Known values + are: "User", "Application", "ManagedIdentity", and "Key". + :vartype last_modified_by_type: str or ~azure.mgmt.cosmosdb.models.CreatedByType + :ivar last_modified_at: The timestamp of resource last modification (UTC). + :vartype last_modified_at: ~datetime.datetime + """ + + _attribute_map = { + "created_by": {"key": "createdBy", "type": "str"}, + "created_by_type": {"key": "createdByType", "type": "str"}, + "created_at": {"key": "createdAt", "type": "iso-8601"}, + "last_modified_by": {"key": "lastModifiedBy", "type": "str"}, + "last_modified_by_type": {"key": "lastModifiedByType", "type": "str"}, + "last_modified_at": {"key": "lastModifiedAt", "type": "iso-8601"}, + } + + def __init__( + self, + *, + created_by: Optional[str] = None, + created_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, + created_at: Optional[datetime.datetime] = None, + last_modified_by: Optional[str] = None, + last_modified_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, + last_modified_at: Optional[datetime.datetime] = None, + **kwargs: Any + ) -> None: + """ + :keyword created_by: The identity that created the resource. + :paramtype created_by: str + :keyword created_by_type: The type of identity that created the resource. Known values are: + "User", "Application", "ManagedIdentity", and "Key". + :paramtype created_by_type: str or ~azure.mgmt.cosmosdb.models.CreatedByType + :keyword created_at: The timestamp of resource creation (UTC). + :paramtype created_at: ~datetime.datetime + :keyword last_modified_by: The identity that last modified the resource. + :paramtype last_modified_by: str + :keyword last_modified_by_type: The type of identity that last modified the resource. Known + values are: "User", "Application", "ManagedIdentity", and "Key". + :paramtype last_modified_by_type: str or ~azure.mgmt.cosmosdb.models.CreatedByType + :keyword last_modified_at: The timestamp of resource last modification (UTC). + :paramtype last_modified_at: ~datetime.datetime + """ + super().__init__(**kwargs) + self.created_by = created_by + self.created_by_type = created_by_type + self.created_at = created_at + self.last_modified_by = last_modified_by + self.last_modified_by_type = last_modified_by_type + self.last_modified_at = last_modified_at + + +class TableCreateUpdateParameters(ARMResourceProperties): + """Parameters to create and update Cosmos DB Table. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: The standard JSON format of a Table. Required. + :vartype resource: ~azure.mgmt.cosmosdb.models.TableResource + :ivar options: A key-value pair of options to be applied for the request. This corresponds to + the headers sent with the request. + :vartype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "resource": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "TableResource"}, + "options": {"key": "properties.options", "type": "CreateUpdateOptions"}, + } + + def __init__( + self, + *, + resource: "_models.TableResource", + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + options: Optional["_models.CreateUpdateOptions"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: The standard JSON format of a Table. Required. + :paramtype resource: ~azure.mgmt.cosmosdb.models.TableResource + :keyword options: A key-value pair of options to be applied for the request. This corresponds + to the headers sent with the request. + :paramtype options: ~azure.mgmt.cosmosdb.models.CreateUpdateOptions + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + self.options = options + + +class TableGetPropertiesOptions(OptionsResource): + """TableGetPropertiesOptions. + + :ivar throughput: Value of the Cosmos DB resource throughput or autoscaleSettings. Use the + ThroughputSetting resource when retrieving offer details. + :vartype throughput: int + :ivar autoscale_settings: Specifies the Autoscale settings. + :vartype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettings + """ + + +class TableResource(_serialization.Model): + """Cosmos DB table resource object. + + All required parameters must be populated in order to send to server. + + :ivar id: Name of the Cosmos DB table. Required. + :vartype id: str + :ivar restore_parameters: Parameters to indicate the information about the restore. + :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" + and "Restore". + :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + """ + + _validation = { + "id": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, + "create_mode": {"key": "createMode", "type": "str"}, + } + + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, + create_mode: Union[str, "_models.CreateMode"] = "Default", + **kwargs: Any + ) -> None: + """ + :keyword id: Name of the Cosmos DB table. Required. + :paramtype id: str + :keyword restore_parameters: Parameters to indicate the information about the restore. + :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: + "Default" and "Restore". + :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + """ + super().__init__(**kwargs) + self.id = id + self.restore_parameters = restore_parameters + self.create_mode = create_mode + + +class TableGetPropertiesResource(TableResource, ExtendedResourceProperties): + """TableGetPropertiesResource. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar rid: A system generated property. A unique identifier. + :vartype rid: str + :ivar ts: A system generated property that denotes the last updated timestamp of the resource. + :vartype ts: float + :ivar etag: A system generated property representing the resource etag required for optimistic + concurrency control. + :vartype etag: str + :ivar id: Name of the Cosmos DB table. Required. + :vartype id: str + :ivar restore_parameters: Parameters to indicate the information about the restore. + :vartype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :ivar create_mode: Enum to indicate the mode of resource creation. Known values are: "Default" + and "Restore". + :vartype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + """ + + _validation = { + "rid": {"readonly": True}, + "ts": {"readonly": True}, + "etag": {"readonly": True}, + "id": {"required": True}, + } + + _attribute_map = { + "rid": {"key": "_rid", "type": "str"}, + "ts": {"key": "_ts", "type": "float"}, + "etag": {"key": "_etag", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "restore_parameters": {"key": "restoreParameters", "type": "ResourceRestoreParameters"}, + "create_mode": {"key": "createMode", "type": "str"}, + } + + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + restore_parameters: Optional["_models.ResourceRestoreParameters"] = None, + create_mode: Union[str, "_models.CreateMode"] = "Default", + **kwargs: Any + ) -> None: + """ + :keyword id: Name of the Cosmos DB table. Required. + :paramtype id: str + :keyword restore_parameters: Parameters to indicate the information about the restore. + :paramtype restore_parameters: ~azure.mgmt.cosmosdb.models.ResourceRestoreParameters + :keyword create_mode: Enum to indicate the mode of resource creation. Known values are: + "Default" and "Restore". + :paramtype create_mode: str or ~azure.mgmt.cosmosdb.models.CreateMode + """ + super().__init__(id=id, restore_parameters=restore_parameters, create_mode=create_mode, **kwargs) + self.rid = None + self.ts = None + self.etag = None + self.id = id + self.restore_parameters = restore_parameters + self.create_mode = create_mode + + +class TableGetResults(ARMResourceProperties): + """An Azure Cosmos DB Table. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: + :vartype resource: ~azure.mgmt.cosmosdb.models.TableGetPropertiesResource + :ivar options: + :vartype options: ~azure.mgmt.cosmosdb.models.TableGetPropertiesOptions + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "TableGetPropertiesResource"}, + "options": {"key": "properties.options", "type": "TableGetPropertiesOptions"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + resource: Optional["_models.TableGetPropertiesResource"] = None, + options: Optional["_models.TableGetPropertiesOptions"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: + :paramtype resource: ~azure.mgmt.cosmosdb.models.TableGetPropertiesResource + :keyword options: + :paramtype options: ~azure.mgmt.cosmosdb.models.TableGetPropertiesOptions + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + self.options = options + + +class TableListResult(_serialization.Model): + """The List operation response, that contains the Table and their properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of Table and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.TableGetResults] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[TableGetResults]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class ThroughputPolicyResource(_serialization.Model): + """Cosmos DB resource throughput policy. + + :ivar is_enabled: Determines whether the ThroughputPolicy is active or not. + :vartype is_enabled: bool + :ivar increment_percent: Represents the percentage by which throughput can increase every time + throughput policy kicks in. + :vartype increment_percent: int + """ + + _attribute_map = { + "is_enabled": {"key": "isEnabled", "type": "bool"}, + "increment_percent": {"key": "incrementPercent", "type": "int"}, + } + + def __init__( + self, *, is_enabled: Optional[bool] = None, increment_percent: Optional[int] = None, **kwargs: Any + ) -> None: + """ + :keyword is_enabled: Determines whether the ThroughputPolicy is active or not. + :paramtype is_enabled: bool + :keyword increment_percent: Represents the percentage by which throughput can increase every + time throughput policy kicks in. + :paramtype increment_percent: int + """ + super().__init__(**kwargs) + self.is_enabled = is_enabled + self.increment_percent = increment_percent + + +class ThroughputPoolAccountCreateParameters(_serialization.Model): + """Parameters for creating a Azure Cosmos DB throughput pool account. + + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar account_resource_identifier: The resource identifier of global database account in the + throughputPool. + :vartype account_resource_identifier: str + :ivar account_location: The location of global database account in the throughputPool. + :vartype account_location: str + """ + + _attribute_map = { + "tags": {"key": "tags", "type": "{str}"}, + "account_resource_identifier": {"key": "properties.accountResourceIdentifier", "type": "str"}, + "account_location": {"key": "properties.accountLocation", "type": "str"}, + } + + def __init__( + self, + *, + tags: Optional[Dict[str, str]] = None, + account_resource_identifier: Optional[str] = None, + account_location: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword account_resource_identifier: The resource identifier of global database account in the + throughputPool. + :paramtype account_resource_identifier: str + :keyword account_location: The location of global database account in the throughputPool. + :paramtype account_location: str + """ + super().__init__(**kwargs) + self.tags = tags + self.account_resource_identifier = account_resource_identifier + self.account_location = account_location + + +class ThroughputPoolAccountResource(ProxyResource): + """An Azure Cosmos DB Throughputpool Account. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.cosmosdb.models.SystemData + :ivar provisioning_state: A provisioning state of the ThroughputPool Account. Known values are: + "Uninitialized", "Initializing", "InternallyReady", "Online", "Deleting", "Succeeded", + "Failed", "Canceled", and "Updating". + :vartype provisioning_state: str or ~azure.mgmt.cosmosdb.models.Status + :ivar account_resource_identifier: The resource identifier of global database account in the + throughputPool. + :vartype account_resource_identifier: str + :ivar account_location: The location of global database account in the throughputPool. + :vartype account_location: str + :ivar account_instance_id: The instance id of global database account in the throughputPool. + :vartype account_instance_id: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + "account_instance_id": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "account_resource_identifier": {"key": "properties.accountResourceIdentifier", "type": "str"}, + "account_location": {"key": "properties.accountLocation", "type": "str"}, + "account_instance_id": {"key": "properties.accountInstanceId", "type": "str"}, + } + + def __init__( + self, + *, + provisioning_state: Optional[Union[str, "_models.Status"]] = None, + account_resource_identifier: Optional[str] = None, + account_location: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword provisioning_state: A provisioning state of the ThroughputPool Account. Known values + are: "Uninitialized", "Initializing", "InternallyReady", "Online", "Deleting", "Succeeded", + "Failed", "Canceled", and "Updating". + :paramtype provisioning_state: str or ~azure.mgmt.cosmosdb.models.Status + :keyword account_resource_identifier: The resource identifier of global database account in the + throughputPool. + :paramtype account_resource_identifier: str + :keyword account_location: The location of global database account in the throughputPool. + :paramtype account_location: str + """ + super().__init__(**kwargs) + self.provisioning_state = provisioning_state + self.account_resource_identifier = account_resource_identifier + self.account_location = account_location + self.account_instance_id = None + + +class ThroughputPoolAccountsListResult(_serialization.Model): + """The List operation response, that contains the global database accounts and their properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of global database accounts in a throughput pool and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.ThroughputPoolAccountResource] + :ivar next_link: The link used to get the next page of results. + :vartype next_link: str + """ + + _validation = { + "value": {"readonly": True}, + "next_link": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[ThroughputPoolAccountResource]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + self.next_link = None + + +class TrackedResource(Resource): + """The resource model definition for an Azure Resource Manager tracked top level resource which + has 'tags' and a 'location'. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.cosmosdb.models.SystemData + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar location: The geo-location where the resource lives. Required. + :vartype location: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + "location": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "tags": {"key": "tags", "type": "{str}"}, + "location": {"key": "location", "type": "str"}, + } + + def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kwargs: Any) -> None: + """ + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword location: The geo-location where the resource lives. Required. + :paramtype location: str + """ + super().__init__(**kwargs) + self.tags = tags + self.location = location + + +class ThroughputPoolResource(TrackedResource): + """An Azure Cosmos DB Throughputpool. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.cosmosdb.models.SystemData + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar location: The geo-location where the resource lives. Required. + :vartype location: str + :ivar provisioning_state: A provisioning state of the ThroughputPool. Known values are: + "Uninitialized", "Initializing", "InternallyReady", "Online", "Deleting", "Succeeded", + "Failed", "Canceled", and "Updating". + :vartype provisioning_state: str or ~azure.mgmt.cosmosdb.models.Status + :ivar max_throughput: Value for throughput to be shared among CosmosDB resources in the pool. + :vartype max_throughput: int + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + "location": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "tags": {"key": "tags", "type": "{str}"}, + "location": {"key": "location", "type": "str"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "max_throughput": {"key": "properties.maxThroughput", "type": "int"}, + } + + def __init__( + self, + *, + location: str, + tags: Optional[Dict[str, str]] = None, + provisioning_state: Optional[Union[str, "_models.Status"]] = None, + max_throughput: Optional[int] = None, + **kwargs: Any + ) -> None: + """ + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword location: The geo-location where the resource lives. Required. + :paramtype location: str + :keyword provisioning_state: A provisioning state of the ThroughputPool. Known values are: + "Uninitialized", "Initializing", "InternallyReady", "Online", "Deleting", "Succeeded", + "Failed", "Canceled", and "Updating". + :paramtype provisioning_state: str or ~azure.mgmt.cosmosdb.models.Status + :keyword max_throughput: Value for throughput to be shared among CosmosDB resources in the + pool. + :paramtype max_throughput: int + """ + super().__init__(tags=tags, location=location, **kwargs) + self.provisioning_state = provisioning_state + self.max_throughput = max_throughput + + +class ThroughputPoolsListResult(_serialization.Model): + """The List operation response, that contains the throughput pools and their properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of throughput pools and their properties. + :vartype value: list[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] + :ivar next_link: The link used to get the next page of results. + :vartype next_link: str + """ + + _validation = { + "value": {"readonly": True}, + "next_link": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[ThroughputPoolResource]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + self.next_link = None + + +class ThroughputPoolUpdate(_serialization.Model): + """Represents a throughput pool resource for updates. + + :ivar provisioning_state: A provisioning state of the ThroughputPool. Known values are: + "Uninitialized", "Initializing", "InternallyReady", "Online", "Deleting", "Succeeded", + "Failed", "Canceled", and "Updating". + :vartype provisioning_state: str or ~azure.mgmt.cosmosdb.models.Status + :ivar max_throughput: Value for throughput to be shared among CosmosDB resources in the pool. + :vartype max_throughput: int + """ + + _attribute_map = { + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "max_throughput": {"key": "properties.maxThroughput", "type": "int"}, + } + + def __init__( + self, + *, + provisioning_state: Optional[Union[str, "_models.Status"]] = None, + max_throughput: Optional[int] = None, + **kwargs: Any + ) -> None: + """ + :keyword provisioning_state: A provisioning state of the ThroughputPool. Known values are: + "Uninitialized", "Initializing", "InternallyReady", "Online", "Deleting", "Succeeded", + "Failed", "Canceled", and "Updating". + :paramtype provisioning_state: str or ~azure.mgmt.cosmosdb.models.Status + :keyword max_throughput: Value for throughput to be shared among CosmosDB resources in the + pool. + :paramtype max_throughput: int + """ + super().__init__(**kwargs) + self.provisioning_state = provisioning_state + self.max_throughput = max_throughput + + +class ThroughputSettingsResource(_serialization.Model): + """Cosmos DB resource throughput object. Either throughput is required or autoscaleSettings is + required, but not both. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar throughput: Value of the Cosmos DB resource throughput. Either throughput is required or + autoscaleSettings is required, but not both. + :vartype throughput: int + :ivar autoscale_settings: Cosmos DB resource for autoscale settings. Either throughput is + required or autoscaleSettings is required, but not both. + :vartype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettingsResource + :ivar minimum_throughput: The minimum throughput of the resource. + :vartype minimum_throughput: str + :ivar offer_replace_pending: The throughput replace is pending. + :vartype offer_replace_pending: str + :ivar instant_maximum_throughput: The offer throughput value to instantly scale up without + triggering splits. + :vartype instant_maximum_throughput: str + :ivar soft_allowed_maximum_throughput: The maximum throughput value or the maximum + maxThroughput value (for autoscale) that can be specified. + :vartype soft_allowed_maximum_throughput: str + """ + + _validation = { + "minimum_throughput": {"readonly": True}, + "offer_replace_pending": {"readonly": True}, + "instant_maximum_throughput": {"readonly": True}, + "soft_allowed_maximum_throughput": {"readonly": True}, + } + + _attribute_map = { + "throughput": {"key": "throughput", "type": "int"}, + "autoscale_settings": {"key": "autoscaleSettings", "type": "AutoscaleSettingsResource"}, + "minimum_throughput": {"key": "minimumThroughput", "type": "str"}, + "offer_replace_pending": {"key": "offerReplacePending", "type": "str"}, + "instant_maximum_throughput": {"key": "instantMaximumThroughput", "type": "str"}, + "soft_allowed_maximum_throughput": {"key": "softAllowedMaximumThroughput", "type": "str"}, + } + + def __init__( + self, + *, + throughput: Optional[int] = None, + autoscale_settings: Optional["_models.AutoscaleSettingsResource"] = None, + **kwargs: Any + ) -> None: + """ + :keyword throughput: Value of the Cosmos DB resource throughput. Either throughput is required + or autoscaleSettings is required, but not both. + :paramtype throughput: int + :keyword autoscale_settings: Cosmos DB resource for autoscale settings. Either throughput is + required or autoscaleSettings is required, but not both. + :paramtype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettingsResource + """ + super().__init__(**kwargs) + self.throughput = throughput + self.autoscale_settings = autoscale_settings + self.minimum_throughput = None + self.offer_replace_pending = None + self.instant_maximum_throughput = None + self.soft_allowed_maximum_throughput = None + + +class ThroughputSettingsGetPropertiesResource(ThroughputSettingsResource, ExtendedResourceProperties): + """ThroughputSettingsGetPropertiesResource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar rid: A system generated property. A unique identifier. + :vartype rid: str + :ivar ts: A system generated property that denotes the last updated timestamp of the resource. + :vartype ts: float + :ivar etag: A system generated property representing the resource etag required for optimistic + concurrency control. + :vartype etag: str + :ivar throughput: Value of the Cosmos DB resource throughput. Either throughput is required or + autoscaleSettings is required, but not both. + :vartype throughput: int + :ivar autoscale_settings: Cosmos DB resource for autoscale settings. Either throughput is + required or autoscaleSettings is required, but not both. + :vartype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettingsResource + :ivar minimum_throughput: The minimum throughput of the resource. + :vartype minimum_throughput: str + :ivar offer_replace_pending: The throughput replace is pending. + :vartype offer_replace_pending: str + :ivar instant_maximum_throughput: The offer throughput value to instantly scale up without + triggering splits. + :vartype instant_maximum_throughput: str + :ivar soft_allowed_maximum_throughput: The maximum throughput value or the maximum + maxThroughput value (for autoscale) that can be specified. + :vartype soft_allowed_maximum_throughput: str + """ + + _validation = { + "rid": {"readonly": True}, + "ts": {"readonly": True}, + "etag": {"readonly": True}, + "minimum_throughput": {"readonly": True}, + "offer_replace_pending": {"readonly": True}, + "instant_maximum_throughput": {"readonly": True}, + "soft_allowed_maximum_throughput": {"readonly": True}, + } + + _attribute_map = { + "rid": {"key": "_rid", "type": "str"}, + "ts": {"key": "_ts", "type": "float"}, + "etag": {"key": "_etag", "type": "str"}, + "throughput": {"key": "throughput", "type": "int"}, + "autoscale_settings": {"key": "autoscaleSettings", "type": "AutoscaleSettingsResource"}, + "minimum_throughput": {"key": "minimumThroughput", "type": "str"}, + "offer_replace_pending": {"key": "offerReplacePending", "type": "str"}, + "instant_maximum_throughput": {"key": "instantMaximumThroughput", "type": "str"}, + "soft_allowed_maximum_throughput": {"key": "softAllowedMaximumThroughput", "type": "str"}, + } + + def __init__( + self, + *, + throughput: Optional[int] = None, + autoscale_settings: Optional["_models.AutoscaleSettingsResource"] = None, + **kwargs: Any + ) -> None: + """ + :keyword throughput: Value of the Cosmos DB resource throughput. Either throughput is required + or autoscaleSettings is required, but not both. + :paramtype throughput: int + :keyword autoscale_settings: Cosmos DB resource for autoscale settings. Either throughput is + required or autoscaleSettings is required, but not both. + :paramtype autoscale_settings: ~azure.mgmt.cosmosdb.models.AutoscaleSettingsResource + """ + super().__init__(throughput=throughput, autoscale_settings=autoscale_settings, **kwargs) + self.rid = None + self.ts = None + self.etag = None + self.throughput = throughput + self.autoscale_settings = autoscale_settings + self.minimum_throughput = None + self.offer_replace_pending = None + self.instant_maximum_throughput = None + self.soft_allowed_maximum_throughput = None + + +class ThroughputSettingsGetResults(ARMResourceProperties): + """An Azure Cosmos DB resource throughput. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: + :vartype resource: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetPropertiesResource + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "ThroughputSettingsGetPropertiesResource"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + resource: Optional["_models.ThroughputSettingsGetPropertiesResource"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: + :paramtype resource: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetPropertiesResource + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + + +class ThroughputSettingsUpdateParameters(ARMResourceProperties): + """Parameters to update Cosmos DB resource throughput. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: The unique resource identifier of the ARM resource. + :vartype id: str + :ivar name: The name of the ARM resource. + :vartype name: str + :ivar type: The type of Azure resource. + :vartype type: str + :ivar location: The location of the resource group to which the resource belongs. + :vartype location: str + :ivar tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :vartype tags: dict[str, str] + :ivar identity: Identity for the resource. + :vartype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :ivar resource: The standard JSON format of a resource throughput. Required. + :vartype resource: ~azure.mgmt.cosmosdb.models.ThroughputSettingsResource + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "resource": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "resource": {"key": "properties.resource", "type": "ThroughputSettingsResource"}, + } + + def __init__( + self, + *, + resource: "_models.ThroughputSettingsResource", + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the resource group to which the resource belongs. + :paramtype location: str + :keyword tags: Tags are a list of key-value pairs that describe the resource. These tags can be + used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can + be provided for a resource. Each tag must have a key no greater than 128 characters and value + no greater than 256 characters. For example, the default experience for a template type is set + with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", + "Graph", "DocumentDB", and "MongoDB". + :paramtype tags: dict[str, str] + :keyword identity: Identity for the resource. + :paramtype identity: ~azure.mgmt.cosmosdb.models.ManagedServiceIdentity + :keyword resource: The standard JSON format of a resource throughput. Required. + :paramtype resource: ~azure.mgmt.cosmosdb.models.ThroughputSettingsResource + """ + super().__init__(location=location, tags=tags, identity=identity, **kwargs) + self.resource = resource + + +class UniqueKey(_serialization.Model): + """The unique key on that enforces uniqueness constraint on documents in the collection in the + Azure Cosmos DB service. + + :ivar paths: List of paths must be unique for each document in the Azure Cosmos DB service. + :vartype paths: list[str] + """ + + _attribute_map = { + "paths": {"key": "paths", "type": "[str]"}, + } + + def __init__(self, *, paths: Optional[List[str]] = None, **kwargs: Any) -> None: + """ + :keyword paths: List of paths must be unique for each document in the Azure Cosmos DB service. + :paramtype paths: list[str] + """ + super().__init__(**kwargs) + self.paths = paths + + +class UniqueKeyPolicy(_serialization.Model): + """The unique key policy configuration for specifying uniqueness constraints on documents in the + collection in the Azure Cosmos DB service. + + :ivar unique_keys: List of unique keys on that enforces uniqueness constraint on documents in + the collection in the Azure Cosmos DB service. + :vartype unique_keys: list[~azure.mgmt.cosmosdb.models.UniqueKey] + """ + + _attribute_map = { + "unique_keys": {"key": "uniqueKeys", "type": "[UniqueKey]"}, + } + + def __init__(self, *, unique_keys: Optional[List["_models.UniqueKey"]] = None, **kwargs: Any) -> None: + """ + :keyword unique_keys: List of unique keys on that enforces uniqueness constraint on documents + in the collection in the Azure Cosmos DB service. + :paramtype unique_keys: list[~azure.mgmt.cosmosdb.models.UniqueKey] + """ + super().__init__(**kwargs) + self.unique_keys = unique_keys + + +class UsagesResult(_serialization.Model): + """The response to a list usage request. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: The list of usages for the database. A usage is a point in time metric. + :vartype value: list[~azure.mgmt.cosmosdb.models.Usage] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[Usage]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class VirtualNetworkRule(_serialization.Model): + """Virtual Network ACL Rule object. + + :ivar id: Resource ID of a subnet, for example: + /subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}. # pylint: disable=line-too-long + :vartype id: str + :ivar ignore_missing_v_net_service_endpoint: Create firewall rule before the virtual network + has vnet service endpoint enabled. + :vartype ignore_missing_v_net_service_endpoint: bool + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "ignore_missing_v_net_service_endpoint": {"key": "ignoreMissingVNetServiceEndpoint", "type": "bool"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + ignore_missing_v_net_service_endpoint: Optional[bool] = None, + **kwargs: Any + ) -> None: + """ + :keyword id: Resource ID of a subnet, for example: + /subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}. # pylint: disable=line-too-long + :paramtype id: str + :keyword ignore_missing_v_net_service_endpoint: Create firewall rule before the virtual network + has vnet service endpoint enabled. + :paramtype ignore_missing_v_net_service_endpoint: bool + """ + super().__init__(**kwargs) + self.id = id + self.ignore_missing_v_net_service_endpoint = ignore_missing_v_net_service_endpoint diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/models/_patch.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/models/_patch.py index 1bb0db275de..f7dd3251033 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/models/_patch.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/models/_patch.py @@ -1,20 +1,20 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/__init__.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/__init__.py index 317f6d4122d..a6aff077c84 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/__init__.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/__init__.py @@ -1,107 +1,107 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._database_accounts_operations import DatabaseAccountsOperations -from ._operations import Operations -from ._database_operations import DatabaseOperations -from ._collection_operations import CollectionOperations -from ._collection_region_operations import CollectionRegionOperations -from ._database_account_region_operations import DatabaseAccountRegionOperations -from ._percentile_source_target_operations import PercentileSourceTargetOperations -from ._percentile_target_operations import PercentileTargetOperations -from ._percentile_operations import PercentileOperations -from ._collection_partition_region_operations import CollectionPartitionRegionOperations -from ._collection_partition_operations import CollectionPartitionOperations -from ._partition_key_range_id_operations import PartitionKeyRangeIdOperations -from ._partition_key_range_id_region_operations import PartitionKeyRangeIdRegionOperations -from ._graph_resources_operations import GraphResourcesOperations -from ._sql_resources_operations import SqlResourcesOperations -from ._mongo_db_resources_operations import MongoDBResourcesOperations -from ._table_resources_operations import TableResourcesOperations -from ._cassandra_resources_operations import CassandraResourcesOperations -from ._gremlin_resources_operations import GremlinResourcesOperations -from ._locations_operations import LocationsOperations -from ._data_transfer_jobs_operations import DataTransferJobsOperations -from ._cassandra_clusters_operations import CassandraClustersOperations -from ._cassandra_data_centers_operations import CassandraDataCentersOperations -from ._network_security_perimeter_configurations_operations import NetworkSecurityPerimeterConfigurationsOperations -from ._notebook_workspaces_operations import NotebookWorkspacesOperations -from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations -from ._private_link_resources_operations import PrivateLinkResourcesOperations -from ._restorable_database_accounts_operations import RestorableDatabaseAccountsOperations -from ._restorable_sql_databases_operations import RestorableSqlDatabasesOperations -from ._restorable_sql_containers_operations import RestorableSqlContainersOperations -from ._restorable_sql_resources_operations import RestorableSqlResourcesOperations -from ._restorable_mongodb_databases_operations import RestorableMongodbDatabasesOperations -from ._restorable_mongodb_collections_operations import RestorableMongodbCollectionsOperations -from ._restorable_mongodb_resources_operations import RestorableMongodbResourcesOperations -from ._restorable_gremlin_databases_operations import RestorableGremlinDatabasesOperations -from ._restorable_gremlin_graphs_operations import RestorableGremlinGraphsOperations -from ._restorable_gremlin_resources_operations import RestorableGremlinResourcesOperations -from ._restorable_tables_operations import RestorableTablesOperations -from ._restorable_table_resources_operations import RestorableTableResourcesOperations -from ._service_operations import ServiceOperations -from ._throughput_pools_operations import ThroughputPoolsOperations -from ._throughput_pool_operations import ThroughputPoolOperations -from ._throughput_pool_accounts_operations import ThroughputPoolAccountsOperations -from ._throughput_pool_account_operations import ThroughputPoolAccountOperations -from ._chaos_fault_operations import ChaosFaultOperations - -from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "DatabaseAccountsOperations", - "Operations", - "DatabaseOperations", - "CollectionOperations", - "CollectionRegionOperations", - "DatabaseAccountRegionOperations", - "PercentileSourceTargetOperations", - "PercentileTargetOperations", - "PercentileOperations", - "CollectionPartitionRegionOperations", - "CollectionPartitionOperations", - "PartitionKeyRangeIdOperations", - "PartitionKeyRangeIdRegionOperations", - "GraphResourcesOperations", - "SqlResourcesOperations", - "MongoDBResourcesOperations", - "TableResourcesOperations", - "CassandraResourcesOperations", - "GremlinResourcesOperations", - "LocationsOperations", - "DataTransferJobsOperations", - "CassandraClustersOperations", - "CassandraDataCentersOperations", - "NetworkSecurityPerimeterConfigurationsOperations", - "NotebookWorkspacesOperations", - "PrivateEndpointConnectionsOperations", - "PrivateLinkResourcesOperations", - "RestorableDatabaseAccountsOperations", - "RestorableSqlDatabasesOperations", - "RestorableSqlContainersOperations", - "RestorableSqlResourcesOperations", - "RestorableMongodbDatabasesOperations", - "RestorableMongodbCollectionsOperations", - "RestorableMongodbResourcesOperations", - "RestorableGremlinDatabasesOperations", - "RestorableGremlinGraphsOperations", - "RestorableGremlinResourcesOperations", - "RestorableTablesOperations", - "RestorableTableResourcesOperations", - "ServiceOperations", - "ThroughputPoolsOperations", - "ThroughputPoolOperations", - "ThroughputPoolAccountsOperations", - "ThroughputPoolAccountOperations", - "ChaosFaultOperations", -] -__all__.extend([p for p in _patch_all if p not in __all__]) -_patch_sdk() +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._database_accounts_operations import DatabaseAccountsOperations +from ._operations import Operations +from ._database_operations import DatabaseOperations +from ._collection_operations import CollectionOperations +from ._collection_region_operations import CollectionRegionOperations +from ._database_account_region_operations import DatabaseAccountRegionOperations +from ._percentile_source_target_operations import PercentileSourceTargetOperations +from ._percentile_target_operations import PercentileTargetOperations +from ._percentile_operations import PercentileOperations +from ._collection_partition_region_operations import CollectionPartitionRegionOperations +from ._collection_partition_operations import CollectionPartitionOperations +from ._partition_key_range_id_operations import PartitionKeyRangeIdOperations +from ._partition_key_range_id_region_operations import PartitionKeyRangeIdRegionOperations +from ._graph_resources_operations import GraphResourcesOperations +from ._sql_resources_operations import SqlResourcesOperations +from ._mongo_db_resources_operations import MongoDBResourcesOperations +from ._table_resources_operations import TableResourcesOperations +from ._cassandra_resources_operations import CassandraResourcesOperations +from ._gremlin_resources_operations import GremlinResourcesOperations +from ._locations_operations import LocationsOperations +from ._data_transfer_jobs_operations import DataTransferJobsOperations +from ._cassandra_clusters_operations import CassandraClustersOperations +from ._cassandra_data_centers_operations import CassandraDataCentersOperations +from ._network_security_perimeter_configurations_operations import NetworkSecurityPerimeterConfigurationsOperations +from ._notebook_workspaces_operations import NotebookWorkspacesOperations +from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations +from ._private_link_resources_operations import PrivateLinkResourcesOperations +from ._restorable_database_accounts_operations import RestorableDatabaseAccountsOperations +from ._restorable_sql_databases_operations import RestorableSqlDatabasesOperations +from ._restorable_sql_containers_operations import RestorableSqlContainersOperations +from ._restorable_sql_resources_operations import RestorableSqlResourcesOperations +from ._restorable_mongodb_databases_operations import RestorableMongodbDatabasesOperations +from ._restorable_mongodb_collections_operations import RestorableMongodbCollectionsOperations +from ._restorable_mongodb_resources_operations import RestorableMongodbResourcesOperations +from ._restorable_gremlin_databases_operations import RestorableGremlinDatabasesOperations +from ._restorable_gremlin_graphs_operations import RestorableGremlinGraphsOperations +from ._restorable_gremlin_resources_operations import RestorableGremlinResourcesOperations +from ._restorable_tables_operations import RestorableTablesOperations +from ._restorable_table_resources_operations import RestorableTableResourcesOperations +from ._service_operations import ServiceOperations +from ._throughput_pools_operations import ThroughputPoolsOperations +from ._throughput_pool_operations import ThroughputPoolOperations +from ._throughput_pool_accounts_operations import ThroughputPoolAccountsOperations +from ._throughput_pool_account_operations import ThroughputPoolAccountOperations +from ._chaos_fault_operations import ChaosFaultOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "DatabaseAccountsOperations", + "Operations", + "DatabaseOperations", + "CollectionOperations", + "CollectionRegionOperations", + "DatabaseAccountRegionOperations", + "PercentileSourceTargetOperations", + "PercentileTargetOperations", + "PercentileOperations", + "CollectionPartitionRegionOperations", + "CollectionPartitionOperations", + "PartitionKeyRangeIdOperations", + "PartitionKeyRangeIdRegionOperations", + "GraphResourcesOperations", + "SqlResourcesOperations", + "MongoDBResourcesOperations", + "TableResourcesOperations", + "CassandraResourcesOperations", + "GremlinResourcesOperations", + "LocationsOperations", + "DataTransferJobsOperations", + "CassandraClustersOperations", + "CassandraDataCentersOperations", + "NetworkSecurityPerimeterConfigurationsOperations", + "NotebookWorkspacesOperations", + "PrivateEndpointConnectionsOperations", + "PrivateLinkResourcesOperations", + "RestorableDatabaseAccountsOperations", + "RestorableSqlDatabasesOperations", + "RestorableSqlContainersOperations", + "RestorableSqlResourcesOperations", + "RestorableMongodbDatabasesOperations", + "RestorableMongodbCollectionsOperations", + "RestorableMongodbResourcesOperations", + "RestorableGremlinDatabasesOperations", + "RestorableGremlinGraphsOperations", + "RestorableGremlinResourcesOperations", + "RestorableTablesOperations", + "RestorableTableResourcesOperations", + "ServiceOperations", + "ThroughputPoolsOperations", + "ThroughputPoolOperations", + "ThroughputPoolAccountsOperations", + "ThroughputPoolAccountOperations", + "ChaosFaultOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_cassandra_clusters_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_cassandra_clusters_operations.py index 59fea2986e2..db4392b3c4f 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_cassandra_clusters_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_cassandra_clusters_operations.py @@ -1,2244 +1,2244 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.arm_polling import ARMPolling - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/cassandraClusters" - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_by_resource_group_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request(resource_group_name: str, cluster_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "clusterName": _SERIALIZER.url( - "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - resource_group_name: str, cluster_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "clusterName": _SERIALIZER.url( - "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_update_request( - resource_group_name: str, cluster_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "clusterName": _SERIALIZER.url( - "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_update_request( - resource_group_name: str, cluster_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "clusterName": _SERIALIZER.url( - "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_invoke_command_request( - resource_group_name: str, cluster_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}/invokeCommand", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "clusterName": _SERIALIZER.url( - "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_invoke_command_async_request( - resource_group_name: str, cluster_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}/invokeCommandAsync", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "clusterName": _SERIALIZER.url( - "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_command_request( - resource_group_name: str, cluster_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}/commands", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "clusterName": _SERIALIZER.url( - "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_command_async_request( - resource_group_name: str, cluster_name: str, command_id: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}/commands/{commandId}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "clusterName": _SERIALIZER.url( - "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" - ), - "commandId": _SERIALIZER.url( - "command_id", command_id, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_backups_request( - resource_group_name: str, cluster_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}/backups", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "clusterName": _SERIALIZER.url( - "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_backup_request( - resource_group_name: str, cluster_name: str, backup_id: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}/backups/{backupId}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "clusterName": _SERIALIZER.url( - "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" - ), - "backupId": _SERIALIZER.url("backup_id", backup_id, "str", max_length=15, min_length=1, pattern=r"^[0-9]+$"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_deallocate_request( - resource_group_name: str, - cluster_name: str, - subscription_id: str, - *, - x_ms_force_deallocate: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}/deallocate", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "clusterName": _SERIALIZER.url( - "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if x_ms_force_deallocate is not None: - _headers["x-ms-force-deallocate"] = _SERIALIZER.header("x_ms_force_deallocate", x_ms_force_deallocate, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_start_request( - resource_group_name: str, cluster_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}/start", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "clusterName": _SERIALIZER.url( - "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_status_request( - resource_group_name: str, cluster_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}/status", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "clusterName": _SERIALIZER.url( - "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class CassandraClustersOperations: # pylint: disable=too-many-public-methods - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`cassandra_clusters` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.ClusterResource"]: - """List all managed Cassandra clusters in this subscription. - - :return: An iterator like instance of either ClusterResource or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.ClusterResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListClusters] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_by_subscription_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("ListClusters", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.ClusterResource"]: - """List all managed Cassandra clusters in this resource group. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :return: An iterator like instance of either ClusterResource or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.ClusterResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListClusters] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_by_resource_group_request( - resource_group_name=resource_group_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("ListClusters", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get(self, resource_group_name: str, cluster_name: str, **kwargs: Any) -> _models.ClusterResource: - """Get the properties of a managed Cassandra cluster. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :return: ClusterResource or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ClusterResource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ClusterResource] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ClusterResource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _delete_initial(self, resource_group_name: str, cluster_name: str, **kwargs: Any) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete(self, resource_group_name: str, cluster_name: str, **kwargs: Any) -> LROPoller[None]: - """Deletes a managed Cassandra cluster. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_initial( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - def _create_update_initial( - self, - resource_group_name: str, - cluster_name: str, - body: Union[_models.ClusterResource, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _json = self._serialize.body(body, "ClusterResource") - - _request = build_create_update_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_update( - self, - resource_group_name: str, - cluster_name: str, - body: _models.ClusterResource, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ClusterResource]: - """Create or update a managed Cassandra cluster. When updating, you must specify all writable - properties. To update only some properties, use PATCH. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param body: The properties specifying the desired state of the managed Cassandra cluster. - Required. - :type body: ~azure.mgmt.cosmosdb.models.ClusterResource - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ClusterResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ClusterResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_update( - self, - resource_group_name: str, - cluster_name: str, - body: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ClusterResource]: - """Create or update a managed Cassandra cluster. When updating, you must specify all writable - properties. To update only some properties, use PATCH. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param body: The properties specifying the desired state of the managed Cassandra cluster. - Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ClusterResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ClusterResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_update( - self, - resource_group_name: str, - cluster_name: str, - body: Union[_models.ClusterResource, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.ClusterResource]: - """Create or update a managed Cassandra cluster. When updating, you must specify all writable - properties. To update only some properties, use PATCH. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param body: The properties specifying the desired state of the managed Cassandra cluster. Is - either a ClusterResource type or a IO[bytes] type. Required. - :type body: ~azure.mgmt.cosmosdb.models.ClusterResource or IO[bytes] - :return: An instance of LROPoller that returns either ClusterResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ClusterResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ClusterResource] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_update_initial( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ClusterResource", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ClusterResource].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ClusterResource]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _update_initial( - self, - resource_group_name: str, - cluster_name: str, - body: Union[_models.ClusterResource, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _json = self._serialize.body(body, "ClusterResource") - - _request = build_update_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_update( - self, - resource_group_name: str, - cluster_name: str, - body: _models.ClusterResource, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ClusterResource]: - """Updates some of the properties of a managed Cassandra cluster. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param body: Parameters to provide for specifying the managed Cassandra cluster. Required. - :type body: ~azure.mgmt.cosmosdb.models.ClusterResource - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ClusterResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ClusterResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_update( - self, - resource_group_name: str, - cluster_name: str, - body: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ClusterResource]: - """Updates some of the properties of a managed Cassandra cluster. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param body: Parameters to provide for specifying the managed Cassandra cluster. Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ClusterResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ClusterResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_update( - self, - resource_group_name: str, - cluster_name: str, - body: Union[_models.ClusterResource, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.ClusterResource]: - """Updates some of the properties of a managed Cassandra cluster. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param body: Parameters to provide for specifying the managed Cassandra cluster. Is either a - ClusterResource type or a IO[bytes] type. Required. - :type body: ~azure.mgmt.cosmosdb.models.ClusterResource or IO[bytes] - :return: An instance of LROPoller that returns either ClusterResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ClusterResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ClusterResource] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._update_initial( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ClusterResource", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ClusterResource].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ClusterResource]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _invoke_command_initial( - self, - resource_group_name: str, - cluster_name: str, - body: Union[_models.CommandPostBody, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _json = self._serialize.body(body, "CommandPostBody") - - _request = build_invoke_command_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_invoke_command( - self, - resource_group_name: str, - cluster_name: str, - body: _models.CommandPostBody, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.CommandOutput]: - """Invoke a command like nodetool for cassandra maintenance. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param body: Specification which command to run where. Required. - :type body: ~azure.mgmt.cosmosdb.models.CommandPostBody - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either CommandOutput or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.CommandOutput] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_invoke_command( - self, - resource_group_name: str, - cluster_name: str, - body: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.CommandOutput]: - """Invoke a command like nodetool for cassandra maintenance. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param body: Specification which command to run where. Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either CommandOutput or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.CommandOutput] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_invoke_command( - self, - resource_group_name: str, - cluster_name: str, - body: Union[_models.CommandPostBody, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.CommandOutput]: - """Invoke a command like nodetool for cassandra maintenance. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param body: Specification which command to run where. Is either a CommandPostBody type or a - IO[bytes] type. Required. - :type body: ~azure.mgmt.cosmosdb.models.CommandPostBody or IO[bytes] - :return: An instance of LROPoller that returns either CommandOutput or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.CommandOutput] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.CommandOutput] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._invoke_command_initial( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("CommandOutput", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.CommandOutput].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.CommandOutput]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _invoke_command_async_initial( - self, - resource_group_name: str, - cluster_name: str, - body: Union[_models.CommandPostBody, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _json = self._serialize.body(body, "CommandPostBody") - - _request = build_invoke_command_async_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_invoke_command_async( - self, - resource_group_name: str, - cluster_name: str, - body: _models.CommandPostBody, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.CommandPublicResource]: - """Invoke a command like nodetool for cassandra maintenance asynchronously. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param body: Specification which command to run where. Required. - :type body: ~azure.mgmt.cosmosdb.models.CommandPostBody - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either CommandPublicResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.CommandPublicResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_invoke_command_async( - self, - resource_group_name: str, - cluster_name: str, - body: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.CommandPublicResource]: - """Invoke a command like nodetool for cassandra maintenance asynchronously. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param body: Specification which command to run where. Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either CommandPublicResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.CommandPublicResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_invoke_command_async( - self, - resource_group_name: str, - cluster_name: str, - body: Union[_models.CommandPostBody, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.CommandPublicResource]: - """Invoke a command like nodetool for cassandra maintenance asynchronously. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param body: Specification which command to run where. Is either a CommandPostBody type or a - IO[bytes] type. Required. - :type body: ~azure.mgmt.cosmosdb.models.CommandPostBody or IO[bytes] - :return: An instance of LROPoller that returns either CommandPublicResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.CommandPublicResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.CommandPublicResource] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._invoke_command_async_initial( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("CommandPublicResource", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.CommandPublicResource].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.CommandPublicResource]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @distributed_trace - def list_command( - self, resource_group_name: str, cluster_name: str, **kwargs: Any - ) -> Iterable["_models.CommandPublicResource"]: - """List all commands currently running on ring info. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :return: An iterator like instance of either CommandPublicResource or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.CommandPublicResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListCommands] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_command_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("ListCommands", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get_command_async( - self, resource_group_name: str, cluster_name: str, command_id: str, **kwargs: Any - ) -> _models.ListCommands: - """Get details about a specified command that was run asynchronously. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param command_id: Managed Cassandra cluster command id. Required. - :type command_id: str - :return: ListCommands or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ListCommands - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListCommands] = kwargs.pop("cls", None) - - _request = build_get_command_async_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - command_id=command_id, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ListCommands", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_backups( - self, resource_group_name: str, cluster_name: str, **kwargs: Any - ) -> Iterable["_models.BackupResource"]: - """List the backups of this cluster that are available to restore. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :return: An iterator like instance of either BackupResource or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.BackupResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListBackups] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_backups_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("ListBackups", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get_backup( - self, resource_group_name: str, cluster_name: str, backup_id: str, **kwargs: Any - ) -> _models.BackupResource: - """Get the properties of an individual backup of this cluster that is available to restore. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param backup_id: Id of a restorable backup of a Cassandra cluster. Required. - :type backup_id: str - :return: BackupResource or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.BackupResource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.BackupResource] = kwargs.pop("cls", None) - - _request = build_get_backup_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - backup_id=backup_id, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("BackupResource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _deallocate_initial( - self, resource_group_name: str, cluster_name: str, x_ms_force_deallocate: Optional[str] = None, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_deallocate_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - subscription_id=self._config.subscription_id, - x_ms_force_deallocate=x_ms_force_deallocate, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_deallocate( - self, resource_group_name: str, cluster_name: str, x_ms_force_deallocate: Optional[str] = None, **kwargs: Any - ) -> LROPoller[None]: - """Deallocate the Managed Cassandra Cluster and Associated Data Centers. Deallocation will - deallocate the host virtual machine of this cluster, and reserved the data disk. This won't do - anything on an already deallocated cluster. Use Start to restart the cluster. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param x_ms_force_deallocate: Force to deallocate a cluster of Cluster Type Production. Force - to deallocate a cluster of Cluster Type Production might cause data loss. Default value is - None. - :type x_ms_force_deallocate: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._deallocate_initial( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - x_ms_force_deallocate=x_ms_force_deallocate, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - def _start_initial(self, resource_group_name: str, cluster_name: str, **kwargs: Any) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_start_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_start(self, resource_group_name: str, cluster_name: str, **kwargs: Any) -> LROPoller[None]: - """Start the Managed Cassandra Cluster and Associated Data Centers. Start will start the host - virtual machine of this cluster with reserved data disk. This won't do anything on an already - running cluster. Use Deallocate to deallocate the cluster. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._start_initial( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace - def status( - self, resource_group_name: str, cluster_name: str, **kwargs: Any - ) -> _models.CassandraClusterPublicStatus: - """Gets the CPU, memory, and disk usage statistics for each Cassandra node in a cluster. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :return: CassandraClusterPublicStatus or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.CassandraClusterPublicStatus - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.CassandraClusterPublicStatus] = kwargs.pop("cls", None) - - _request = build_status_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("CassandraClusterPublicStatus", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/cassandraClusters" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_resource_group_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(resource_group_name: str, cluster_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "clusterName": _SERIALIZER.url( + "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, cluster_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "clusterName": _SERIALIZER.url( + "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_update_request( + resource_group_name: str, cluster_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "clusterName": _SERIALIZER.url( + "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_request( + resource_group_name: str, cluster_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "clusterName": _SERIALIZER.url( + "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_invoke_command_request( + resource_group_name: str, cluster_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}/invokeCommand", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "clusterName": _SERIALIZER.url( + "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_invoke_command_async_request( + resource_group_name: str, cluster_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}/invokeCommandAsync", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "clusterName": _SERIALIZER.url( + "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_command_request( + resource_group_name: str, cluster_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}/commands", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "clusterName": _SERIALIZER.url( + "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_command_async_request( + resource_group_name: str, cluster_name: str, command_id: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}/commands/{commandId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "clusterName": _SERIALIZER.url( + "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" + ), + "commandId": _SERIALIZER.url( + "command_id", command_id, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_backups_request( + resource_group_name: str, cluster_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}/backups", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "clusterName": _SERIALIZER.url( + "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_backup_request( + resource_group_name: str, cluster_name: str, backup_id: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}/backups/{backupId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "clusterName": _SERIALIZER.url( + "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" + ), + "backupId": _SERIALIZER.url("backup_id", backup_id, "str", max_length=15, min_length=1, pattern=r"^[0-9]+$"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_deallocate_request( + resource_group_name: str, + cluster_name: str, + subscription_id: str, + *, + x_ms_force_deallocate: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}/deallocate", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "clusterName": _SERIALIZER.url( + "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if x_ms_force_deallocate is not None: + _headers["x-ms-force-deallocate"] = _SERIALIZER.header("x_ms_force_deallocate", x_ms_force_deallocate, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_start_request( + resource_group_name: str, cluster_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}/start", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "clusterName": _SERIALIZER.url( + "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_status_request( + resource_group_name: str, cluster_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}/status", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "clusterName": _SERIALIZER.url( + "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class CassandraClustersOperations: # pylint: disable=too-many-public-methods + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`cassandra_clusters` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.ClusterResource"]: + """List all managed Cassandra clusters in this subscription. + + :return: An iterator like instance of either ClusterResource or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.ClusterResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ListClusters] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_subscription_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ListClusters", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.ClusterResource"]: + """List all managed Cassandra clusters in this resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :return: An iterator like instance of either ClusterResource or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.ClusterResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ListClusters] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ListClusters", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get(self, resource_group_name: str, cluster_name: str, **kwargs: Any) -> _models.ClusterResource: + """Get the properties of a managed Cassandra cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :return: ClusterResource or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ClusterResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ClusterResource] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ClusterResource", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _delete_initial(self, resource_group_name: str, cluster_name: str, **kwargs: Any) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete(self, resource_group_name: str, cluster_name: str, **kwargs: Any) -> LROPoller[None]: + """Deletes a managed Cassandra cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + def _create_update_initial( + self, + resource_group_name: str, + cluster_name: str, + body: Union[_models.ClusterResource, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "ClusterResource") + + _request = build_create_update_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_update( + self, + resource_group_name: str, + cluster_name: str, + body: _models.ClusterResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ClusterResource]: + """Create or update a managed Cassandra cluster. When updating, you must specify all writable + properties. To update only some properties, use PATCH. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param body: The properties specifying the desired state of the managed Cassandra cluster. + Required. + :type body: ~azure.mgmt.cosmosdb.models.ClusterResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ClusterResource or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ClusterResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_update( + self, + resource_group_name: str, + cluster_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ClusterResource]: + """Create or update a managed Cassandra cluster. When updating, you must specify all writable + properties. To update only some properties, use PATCH. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param body: The properties specifying the desired state of the managed Cassandra cluster. + Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ClusterResource or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ClusterResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_update( + self, + resource_group_name: str, + cluster_name: str, + body: Union[_models.ClusterResource, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.ClusterResource]: + """Create or update a managed Cassandra cluster. When updating, you must specify all writable + properties. To update only some properties, use PATCH. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param body: The properties specifying the desired state of the managed Cassandra cluster. Is + either a ClusterResource type or a IO[bytes] type. Required. + :type body: ~azure.mgmt.cosmosdb.models.ClusterResource or IO[bytes] + :return: An instance of LROPoller that returns either ClusterResource or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ClusterResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ClusterResource] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_update_initial( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + body=body, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ClusterResource", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ClusterResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ClusterResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _update_initial( + self, + resource_group_name: str, + cluster_name: str, + body: Union[_models.ClusterResource, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "ClusterResource") + + _request = build_update_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_update( + self, + resource_group_name: str, + cluster_name: str, + body: _models.ClusterResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ClusterResource]: + """Updates some of the properties of a managed Cassandra cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param body: Parameters to provide for specifying the managed Cassandra cluster. Required. + :type body: ~azure.mgmt.cosmosdb.models.ClusterResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ClusterResource or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ClusterResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update( + self, + resource_group_name: str, + cluster_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ClusterResource]: + """Updates some of the properties of a managed Cassandra cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param body: Parameters to provide for specifying the managed Cassandra cluster. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ClusterResource or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ClusterResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update( + self, + resource_group_name: str, + cluster_name: str, + body: Union[_models.ClusterResource, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.ClusterResource]: + """Updates some of the properties of a managed Cassandra cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param body: Parameters to provide for specifying the managed Cassandra cluster. Is either a + ClusterResource type or a IO[bytes] type. Required. + :type body: ~azure.mgmt.cosmosdb.models.ClusterResource or IO[bytes] + :return: An instance of LROPoller that returns either ClusterResource or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ClusterResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ClusterResource] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._update_initial( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + body=body, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ClusterResource", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ClusterResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ClusterResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _invoke_command_initial( + self, + resource_group_name: str, + cluster_name: str, + body: Union[_models.CommandPostBody, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "CommandPostBody") + + _request = build_invoke_command_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_invoke_command( + self, + resource_group_name: str, + cluster_name: str, + body: _models.CommandPostBody, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.CommandOutput]: + """Invoke a command like nodetool for cassandra maintenance. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param body: Specification which command to run where. Required. + :type body: ~azure.mgmt.cosmosdb.models.CommandPostBody + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either CommandOutput or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.CommandOutput] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_invoke_command( + self, + resource_group_name: str, + cluster_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.CommandOutput]: + """Invoke a command like nodetool for cassandra maintenance. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param body: Specification which command to run where. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either CommandOutput or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.CommandOutput] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_invoke_command( + self, + resource_group_name: str, + cluster_name: str, + body: Union[_models.CommandPostBody, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.CommandOutput]: + """Invoke a command like nodetool for cassandra maintenance. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param body: Specification which command to run where. Is either a CommandPostBody type or a + IO[bytes] type. Required. + :type body: ~azure.mgmt.cosmosdb.models.CommandPostBody or IO[bytes] + :return: An instance of LROPoller that returns either CommandOutput or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.CommandOutput] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CommandOutput] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._invoke_command_initial( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + body=body, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("CommandOutput", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.CommandOutput].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.CommandOutput]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _invoke_command_async_initial( + self, + resource_group_name: str, + cluster_name: str, + body: Union[_models.CommandPostBody, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "CommandPostBody") + + _request = build_invoke_command_async_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_invoke_command_async( + self, + resource_group_name: str, + cluster_name: str, + body: _models.CommandPostBody, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.CommandPublicResource]: + """Invoke a command like nodetool for cassandra maintenance asynchronously. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param body: Specification which command to run where. Required. + :type body: ~azure.mgmt.cosmosdb.models.CommandPostBody + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either CommandPublicResource or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.CommandPublicResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_invoke_command_async( + self, + resource_group_name: str, + cluster_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.CommandPublicResource]: + """Invoke a command like nodetool for cassandra maintenance asynchronously. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param body: Specification which command to run where. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either CommandPublicResource or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.CommandPublicResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_invoke_command_async( + self, + resource_group_name: str, + cluster_name: str, + body: Union[_models.CommandPostBody, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.CommandPublicResource]: + """Invoke a command like nodetool for cassandra maintenance asynchronously. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param body: Specification which command to run where. Is either a CommandPostBody type or a + IO[bytes] type. Required. + :type body: ~azure.mgmt.cosmosdb.models.CommandPostBody or IO[bytes] + :return: An instance of LROPoller that returns either CommandPublicResource or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.CommandPublicResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CommandPublicResource] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._invoke_command_async_initial( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + body=body, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("CommandPublicResource", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.CommandPublicResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.CommandPublicResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def list_command( + self, resource_group_name: str, cluster_name: str, **kwargs: Any + ) -> Iterable["_models.CommandPublicResource"]: + """List all commands currently running on ring info. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :return: An iterator like instance of either CommandPublicResource or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.CommandPublicResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ListCommands] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_command_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ListCommands", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get_command_async( + self, resource_group_name: str, cluster_name: str, command_id: str, **kwargs: Any + ) -> _models.ListCommands: + """Get details about a specified command that was run asynchronously. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param command_id: Managed Cassandra cluster command id. Required. + :type command_id: str + :return: ListCommands or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ListCommands + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ListCommands] = kwargs.pop("cls", None) + + _request = build_get_command_async_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + command_id=command_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ListCommands", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_backups( + self, resource_group_name: str, cluster_name: str, **kwargs: Any + ) -> Iterable["_models.BackupResource"]: + """List the backups of this cluster that are available to restore. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :return: An iterator like instance of either BackupResource or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.BackupResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ListBackups] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_backups_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ListBackups", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get_backup( + self, resource_group_name: str, cluster_name: str, backup_id: str, **kwargs: Any + ) -> _models.BackupResource: + """Get the properties of an individual backup of this cluster that is available to restore. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param backup_id: Id of a restorable backup of a Cassandra cluster. Required. + :type backup_id: str + :return: BackupResource or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.BackupResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.BackupResource] = kwargs.pop("cls", None) + + _request = build_get_backup_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + backup_id=backup_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("BackupResource", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _deallocate_initial( + self, resource_group_name: str, cluster_name: str, x_ms_force_deallocate: Optional[str] = None, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_deallocate_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + subscription_id=self._config.subscription_id, + x_ms_force_deallocate=x_ms_force_deallocate, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_deallocate( + self, resource_group_name: str, cluster_name: str, x_ms_force_deallocate: Optional[str] = None, **kwargs: Any + ) -> LROPoller[None]: + """Deallocate the Managed Cassandra Cluster and Associated Data Centers. Deallocation will + deallocate the host virtual machine of this cluster, and reserved the data disk. This won't do + anything on an already deallocated cluster. Use Start to restart the cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param x_ms_force_deallocate: Force to deallocate a cluster of Cluster Type Production. Force + to deallocate a cluster of Cluster Type Production might cause data loss. Default value is + None. + :type x_ms_force_deallocate: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._deallocate_initial( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + x_ms_force_deallocate=x_ms_force_deallocate, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + def _start_initial(self, resource_group_name: str, cluster_name: str, **kwargs: Any) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_start_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_start(self, resource_group_name: str, cluster_name: str, **kwargs: Any) -> LROPoller[None]: + """Start the Managed Cassandra Cluster and Associated Data Centers. Start will start the host + virtual machine of this cluster with reserved data disk. This won't do anything on an already + running cluster. Use Deallocate to deallocate the cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._start_initial( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def status( + self, resource_group_name: str, cluster_name: str, **kwargs: Any + ) -> _models.CassandraClusterPublicStatus: + """Gets the CPU, memory, and disk usage statistics for each Cassandra node in a cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :return: CassandraClusterPublicStatus or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.CassandraClusterPublicStatus + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.CassandraClusterPublicStatus] = kwargs.pop("cls", None) + + _request = build_status_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("CassandraClusterPublicStatus", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_cassandra_data_centers_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_cassandra_data_centers_operations.py index d35423655a6..c5ebd825dfd 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_cassandra_data_centers_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_cassandra_data_centers_operations.py @@ -1,938 +1,938 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.arm_polling import ARMPolling - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_request(resource_group_name: str, cluster_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}/dataCenters", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "clusterName": _SERIALIZER.url( - "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request( - resource_group_name: str, cluster_name: str, data_center_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}/dataCenters/{dataCenterName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "clusterName": _SERIALIZER.url( - "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" - ), - "dataCenterName": _SERIALIZER.url( - "data_center_name", - data_center_name, - "str", - max_length=100, - min_length=1, - pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - resource_group_name: str, cluster_name: str, data_center_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}/dataCenters/{dataCenterName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "clusterName": _SERIALIZER.url( - "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" - ), - "dataCenterName": _SERIALIZER.url( - "data_center_name", - data_center_name, - "str", - max_length=100, - min_length=1, - pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_update_request( - resource_group_name: str, cluster_name: str, data_center_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}/dataCenters/{dataCenterName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "clusterName": _SERIALIZER.url( - "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" - ), - "dataCenterName": _SERIALIZER.url( - "data_center_name", - data_center_name, - "str", - max_length=100, - min_length=1, - pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_update_request( - resource_group_name: str, cluster_name: str, data_center_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}/dataCenters/{dataCenterName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "clusterName": _SERIALIZER.url( - "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" - ), - "dataCenterName": _SERIALIZER.url( - "data_center_name", - data_center_name, - "str", - max_length=100, - min_length=1, - pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) - - -class CassandraDataCentersOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`cassandra_data_centers` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, resource_group_name: str, cluster_name: str, **kwargs: Any - ) -> Iterable["_models.DataCenterResource"]: - """List all data centers in a particular managed Cassandra cluster. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :return: An iterator like instance of either DataCenterResource or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.DataCenterResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ListDataCenters] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("ListDataCenters", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get( - self, resource_group_name: str, cluster_name: str, data_center_name: str, **kwargs: Any - ) -> _models.DataCenterResource: - """Get the properties of a managed Cassandra data center. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param data_center_name: Data center name in a managed Cassandra cluster. Required. - :type data_center_name: str - :return: DataCenterResource or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.DataCenterResource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DataCenterResource] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - data_center_name=data_center_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DataCenterResource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _delete_initial( - self, resource_group_name: str, cluster_name: str, data_center_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - data_center_name=data_center_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete( - self, resource_group_name: str, cluster_name: str, data_center_name: str, **kwargs: Any - ) -> LROPoller[None]: - """Delete a managed Cassandra data center. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param data_center_name: Data center name in a managed Cassandra cluster. Required. - :type data_center_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_initial( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - data_center_name=data_center_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - def _create_update_initial( - self, - resource_group_name: str, - cluster_name: str, - data_center_name: str, - body: Union[_models.DataCenterResource, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _json = self._serialize.body(body, "DataCenterResource") - - _request = build_create_update_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - data_center_name=data_center_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_update( - self, - resource_group_name: str, - cluster_name: str, - data_center_name: str, - body: _models.DataCenterResource, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.DataCenterResource]: - """Create or update a managed Cassandra data center. When updating, overwrite all properties. To - update only some properties, use PATCH. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param data_center_name: Data center name in a managed Cassandra cluster. Required. - :type data_center_name: str - :param body: Parameters specifying the managed Cassandra data center. Required. - :type body: ~azure.mgmt.cosmosdb.models.DataCenterResource - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either DataCenterResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.DataCenterResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_update( - self, - resource_group_name: str, - cluster_name: str, - data_center_name: str, - body: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.DataCenterResource]: - """Create or update a managed Cassandra data center. When updating, overwrite all properties. To - update only some properties, use PATCH. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param data_center_name: Data center name in a managed Cassandra cluster. Required. - :type data_center_name: str - :param body: Parameters specifying the managed Cassandra data center. Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either DataCenterResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.DataCenterResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_update( - self, - resource_group_name: str, - cluster_name: str, - data_center_name: str, - body: Union[_models.DataCenterResource, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.DataCenterResource]: - """Create or update a managed Cassandra data center. When updating, overwrite all properties. To - update only some properties, use PATCH. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param data_center_name: Data center name in a managed Cassandra cluster. Required. - :type data_center_name: str - :param body: Parameters specifying the managed Cassandra data center. Is either a - DataCenterResource type or a IO[bytes] type. Required. - :type body: ~azure.mgmt.cosmosdb.models.DataCenterResource or IO[bytes] - :return: An instance of LROPoller that returns either DataCenterResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.DataCenterResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.DataCenterResource] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_update_initial( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - data_center_name=data_center_name, - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("DataCenterResource", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.DataCenterResource].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.DataCenterResource]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _update_initial( - self, - resource_group_name: str, - cluster_name: str, - data_center_name: str, - body: Union[_models.DataCenterResource, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _json = self._serialize.body(body, "DataCenterResource") - - _request = build_update_request( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - data_center_name=data_center_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_update( - self, - resource_group_name: str, - cluster_name: str, - data_center_name: str, - body: _models.DataCenterResource, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.DataCenterResource]: - """Update some of the properties of a managed Cassandra data center. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param data_center_name: Data center name in a managed Cassandra cluster. Required. - :type data_center_name: str - :param body: Parameters to provide for specifying the managed Cassandra data center. Required. - :type body: ~azure.mgmt.cosmosdb.models.DataCenterResource - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either DataCenterResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.DataCenterResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_update( - self, - resource_group_name: str, - cluster_name: str, - data_center_name: str, - body: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.DataCenterResource]: - """Update some of the properties of a managed Cassandra data center. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param data_center_name: Data center name in a managed Cassandra cluster. Required. - :type data_center_name: str - :param body: Parameters to provide for specifying the managed Cassandra data center. Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either DataCenterResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.DataCenterResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_update( - self, - resource_group_name: str, - cluster_name: str, - data_center_name: str, - body: Union[_models.DataCenterResource, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.DataCenterResource]: - """Update some of the properties of a managed Cassandra data center. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cluster_name: Managed Cassandra cluster name. Required. - :type cluster_name: str - :param data_center_name: Data center name in a managed Cassandra cluster. Required. - :type data_center_name: str - :param body: Parameters to provide for specifying the managed Cassandra data center. Is either - a DataCenterResource type or a IO[bytes] type. Required. - :type body: ~azure.mgmt.cosmosdb.models.DataCenterResource or IO[bytes] - :return: An instance of LROPoller that returns either DataCenterResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.DataCenterResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.DataCenterResource] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._update_initial( - resource_group_name=resource_group_name, - cluster_name=cluster_name, - data_center_name=data_center_name, - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("DataCenterResource", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.DataCenterResource].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.DataCenterResource]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(resource_group_name: str, cluster_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}/dataCenters", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "clusterName": _SERIALIZER.url( + "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request( + resource_group_name: str, cluster_name: str, data_center_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}/dataCenters/{dataCenterName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "clusterName": _SERIALIZER.url( + "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" + ), + "dataCenterName": _SERIALIZER.url( + "data_center_name", + data_center_name, + "str", + max_length=100, + min_length=1, + pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, cluster_name: str, data_center_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}/dataCenters/{dataCenterName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "clusterName": _SERIALIZER.url( + "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" + ), + "dataCenterName": _SERIALIZER.url( + "data_center_name", + data_center_name, + "str", + max_length=100, + min_length=1, + pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_update_request( + resource_group_name: str, cluster_name: str, data_center_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}/dataCenters/{dataCenterName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "clusterName": _SERIALIZER.url( + "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" + ), + "dataCenterName": _SERIALIZER.url( + "data_center_name", + data_center_name, + "str", + max_length=100, + min_length=1, + pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_request( + resource_group_name: str, cluster_name: str, data_center_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}/dataCenters/{dataCenterName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "clusterName": _SERIALIZER.url( + "cluster_name", cluster_name, "str", max_length=100, min_length=1, pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$" + ), + "dataCenterName": _SERIALIZER.url( + "data_center_name", + data_center_name, + "str", + max_length=100, + min_length=1, + pattern=r"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +class CassandraDataCentersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`cassandra_data_centers` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, resource_group_name: str, cluster_name: str, **kwargs: Any + ) -> Iterable["_models.DataCenterResource"]: + """List all data centers in a particular managed Cassandra cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :return: An iterator like instance of either DataCenterResource or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.DataCenterResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ListDataCenters] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ListDataCenters", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get( + self, resource_group_name: str, cluster_name: str, data_center_name: str, **kwargs: Any + ) -> _models.DataCenterResource: + """Get the properties of a managed Cassandra data center. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param data_center_name: Data center name in a managed Cassandra cluster. Required. + :type data_center_name: str + :return: DataCenterResource or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.DataCenterResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DataCenterResource] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + data_center_name=data_center_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DataCenterResource", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _delete_initial( + self, resource_group_name: str, cluster_name: str, data_center_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + data_center_name=data_center_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete( + self, resource_group_name: str, cluster_name: str, data_center_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Delete a managed Cassandra data center. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param data_center_name: Data center name in a managed Cassandra cluster. Required. + :type data_center_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + data_center_name=data_center_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + def _create_update_initial( + self, + resource_group_name: str, + cluster_name: str, + data_center_name: str, + body: Union[_models.DataCenterResource, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "DataCenterResource") + + _request = build_create_update_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + data_center_name=data_center_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_update( + self, + resource_group_name: str, + cluster_name: str, + data_center_name: str, + body: _models.DataCenterResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DataCenterResource]: + """Create or update a managed Cassandra data center. When updating, overwrite all properties. To + update only some properties, use PATCH. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param data_center_name: Data center name in a managed Cassandra cluster. Required. + :type data_center_name: str + :param body: Parameters specifying the managed Cassandra data center. Required. + :type body: ~azure.mgmt.cosmosdb.models.DataCenterResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either DataCenterResource or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.DataCenterResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_update( + self, + resource_group_name: str, + cluster_name: str, + data_center_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DataCenterResource]: + """Create or update a managed Cassandra data center. When updating, overwrite all properties. To + update only some properties, use PATCH. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param data_center_name: Data center name in a managed Cassandra cluster. Required. + :type data_center_name: str + :param body: Parameters specifying the managed Cassandra data center. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either DataCenterResource or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.DataCenterResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_update( + self, + resource_group_name: str, + cluster_name: str, + data_center_name: str, + body: Union[_models.DataCenterResource, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.DataCenterResource]: + """Create or update a managed Cassandra data center. When updating, overwrite all properties. To + update only some properties, use PATCH. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param data_center_name: Data center name in a managed Cassandra cluster. Required. + :type data_center_name: str + :param body: Parameters specifying the managed Cassandra data center. Is either a + DataCenterResource type or a IO[bytes] type. Required. + :type body: ~azure.mgmt.cosmosdb.models.DataCenterResource or IO[bytes] + :return: An instance of LROPoller that returns either DataCenterResource or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.DataCenterResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DataCenterResource] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_update_initial( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + data_center_name=data_center_name, + body=body, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("DataCenterResource", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.DataCenterResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.DataCenterResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _update_initial( + self, + resource_group_name: str, + cluster_name: str, + data_center_name: str, + body: Union[_models.DataCenterResource, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "DataCenterResource") + + _request = build_update_request( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + data_center_name=data_center_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_update( + self, + resource_group_name: str, + cluster_name: str, + data_center_name: str, + body: _models.DataCenterResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DataCenterResource]: + """Update some of the properties of a managed Cassandra data center. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param data_center_name: Data center name in a managed Cassandra cluster. Required. + :type data_center_name: str + :param body: Parameters to provide for specifying the managed Cassandra data center. Required. + :type body: ~azure.mgmt.cosmosdb.models.DataCenterResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either DataCenterResource or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.DataCenterResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update( + self, + resource_group_name: str, + cluster_name: str, + data_center_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DataCenterResource]: + """Update some of the properties of a managed Cassandra data center. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param data_center_name: Data center name in a managed Cassandra cluster. Required. + :type data_center_name: str + :param body: Parameters to provide for specifying the managed Cassandra data center. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either DataCenterResource or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.DataCenterResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update( + self, + resource_group_name: str, + cluster_name: str, + data_center_name: str, + body: Union[_models.DataCenterResource, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.DataCenterResource]: + """Update some of the properties of a managed Cassandra data center. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cluster_name: Managed Cassandra cluster name. Required. + :type cluster_name: str + :param data_center_name: Data center name in a managed Cassandra cluster. Required. + :type data_center_name: str + :param body: Parameters to provide for specifying the managed Cassandra data center. Is either + a DataCenterResource type or a IO[bytes] type. Required. + :type body: ~azure.mgmt.cosmosdb.models.DataCenterResource or IO[bytes] + :return: An instance of LROPoller that returns either DataCenterResource or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.DataCenterResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DataCenterResource] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._update_initial( + resource_group_name=resource_group_name, + cluster_name=cluster_name, + data_center_name=data_center_name, + body=body, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("DataCenterResource", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.DataCenterResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.DataCenterResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_cassandra_resources_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_cassandra_resources_operations.py index 457e1a2f3c3..8cb21dd3b53 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_cassandra_resources_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_cassandra_resources_operations.py @@ -1,4056 +1,4056 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.arm_polling import ARMPolling - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_cassandra_keyspaces_request( - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_cassandra_keyspace_request( - resource_group_name: str, account_name: str, keyspace_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_update_cassandra_keyspace_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, keyspace_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_cassandra_keyspace_request( - resource_group_name: str, account_name: str, keyspace_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) - - -def build_get_cassandra_keyspace_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, keyspace_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/throughputSettings/default", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_update_cassandra_keyspace_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, keyspace_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/throughputSettings/default", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_migrate_cassandra_keyspace_to_autoscale_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, keyspace_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/throughputSettings/default/migrateToAutoscale", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_migrate_cassandra_keyspace_to_manual_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, keyspace_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/throughputSettings/default/migrateToManualThroughput", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_cassandra_tables_request( - resource_group_name: str, account_name: str, keyspace_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/tables", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_cassandra_table_request( - resource_group_name: str, - account_name: str, - keyspace_name: str, - table_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/tables/{tableName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), - "tableName": _SERIALIZER.url("table_name", table_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_update_cassandra_table_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - keyspace_name: str, - table_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/tables/{tableName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), - "tableName": _SERIALIZER.url("table_name", table_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_cassandra_table_request( - resource_group_name: str, - account_name: str, - keyspace_name: str, - table_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/tables/{tableName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), - "tableName": _SERIALIZER.url("table_name", table_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) - - -def build_get_cassandra_table_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - keyspace_name: str, - table_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/tables/{tableName}/throughputSettings/default", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), - "tableName": _SERIALIZER.url("table_name", table_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_update_cassandra_table_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - keyspace_name: str, - table_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/tables/{tableName}/throughputSettings/default", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), - "tableName": _SERIALIZER.url("table_name", table_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_migrate_cassandra_table_to_autoscale_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - keyspace_name: str, - table_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/tables/{tableName}/throughputSettings/default/migrateToAutoscale", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), - "tableName": _SERIALIZER.url("table_name", table_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_migrate_cassandra_table_to_manual_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - keyspace_name: str, - table_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/tables/{tableName}/throughputSettings/default/migrateToManualThroughput", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), - "tableName": _SERIALIZER.url("table_name", table_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_cassandra_views_request( - resource_group_name: str, account_name: str, keyspace_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/views", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_cassandra_view_request( - resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/views/{viewName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), - "viewName": _SERIALIZER.url("view_name", view_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_update_cassandra_view_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/views/{viewName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), - "viewName": _SERIALIZER.url("view_name", view_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_cassandra_view_request( - resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/views/{viewName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), - "viewName": _SERIALIZER.url("view_name", view_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) - - -def build_get_cassandra_view_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/views/{viewName}/throughputSettings/default", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), - "viewName": _SERIALIZER.url("view_name", view_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_update_cassandra_view_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/views/{viewName}/throughputSettings/default", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), - "viewName": _SERIALIZER.url("view_name", view_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_migrate_cassandra_view_to_autoscale_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/views/{viewName}/throughputSettings/default/migrateToAutoscale", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), - "viewName": _SERIALIZER.url("view_name", view_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_migrate_cassandra_view_to_manual_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/views/{viewName}/throughputSettings/default/migrateToManualThroughput", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), - "viewName": _SERIALIZER.url("view_name", view_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -class CassandraResourcesOperations: # pylint: disable=too-many-public-methods - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`cassandra_resources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_cassandra_keyspaces( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> Iterable["_models.CassandraKeyspaceGetResults"]: - """Lists the Cassandra keyspaces under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either CassandraKeyspaceGetResults or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.CassandraKeyspaceGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.CassandraKeyspaceListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_cassandra_keyspaces_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("CassandraKeyspaceListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get_cassandra_keyspace( - self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any - ) -> _models.CassandraKeyspaceGetResults: - """Gets the Cassandra keyspaces under an existing Azure Cosmos DB database account with the - provided name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :return: CassandraKeyspaceGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.CassandraKeyspaceGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.CassandraKeyspaceGetResults] = kwargs.pop("cls", None) - - _request = build_get_cassandra_keyspace_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("CassandraKeyspaceGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _create_update_cassandra_keyspace_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - create_update_cassandra_keyspace_parameters: Union[_models.CassandraKeyspaceCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_cassandra_keyspace_parameters, (IOBase, bytes)): - _content = create_update_cassandra_keyspace_parameters - else: - _json = self._serialize.body( - create_update_cassandra_keyspace_parameters, "CassandraKeyspaceCreateUpdateParameters" - ) - - _request = build_create_update_cassandra_keyspace_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_update_cassandra_keyspace( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - create_update_cassandra_keyspace_parameters: _models.CassandraKeyspaceCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.CassandraKeyspaceGetResults]: - """Create or update an Azure Cosmos DB Cassandra keyspace. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param create_update_cassandra_keyspace_parameters: The parameters to provide for the current - Cassandra keyspace. Required. - :type create_update_cassandra_keyspace_parameters: - ~azure.mgmt.cosmosdb.models.CassandraKeyspaceCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either CassandraKeyspaceGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.CassandraKeyspaceGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_update_cassandra_keyspace( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - create_update_cassandra_keyspace_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.CassandraKeyspaceGetResults]: - """Create or update an Azure Cosmos DB Cassandra keyspace. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param create_update_cassandra_keyspace_parameters: The parameters to provide for the current - Cassandra keyspace. Required. - :type create_update_cassandra_keyspace_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either CassandraKeyspaceGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.CassandraKeyspaceGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_update_cassandra_keyspace( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - create_update_cassandra_keyspace_parameters: Union[_models.CassandraKeyspaceCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.CassandraKeyspaceGetResults]: - """Create or update an Azure Cosmos DB Cassandra keyspace. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param create_update_cassandra_keyspace_parameters: The parameters to provide for the current - Cassandra keyspace. Is either a CassandraKeyspaceCreateUpdateParameters type or a IO[bytes] - type. Required. - :type create_update_cassandra_keyspace_parameters: - ~azure.mgmt.cosmosdb.models.CassandraKeyspaceCreateUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either CassandraKeyspaceGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.CassandraKeyspaceGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.CassandraKeyspaceGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_update_cassandra_keyspace_initial( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - create_update_cassandra_keyspace_parameters=create_update_cassandra_keyspace_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("CassandraKeyspaceGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.CassandraKeyspaceGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.CassandraKeyspaceGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _delete_cassandra_keyspace_initial( - self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_cassandra_keyspace_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete_cassandra_keyspace( - self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any - ) -> LROPoller[None]: - """Deletes an existing Azure Cosmos DB Cassandra keyspace. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_cassandra_keyspace_initial( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace - def get_cassandra_keyspace_throughput( - self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any - ) -> _models.ThroughputSettingsGetResults: - """Gets the RUs per second of the Cassandra Keyspace under an existing Azure Cosmos DB database - account with the provided name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :return: ThroughputSettingsGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - - _request = build_get_cassandra_keyspace_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _update_cassandra_keyspace_throughput_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(update_throughput_parameters, (IOBase, bytes)): - _content = update_throughput_parameters - else: - _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") - - _request = build_update_cassandra_keyspace_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_update_cassandra_keyspace_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Cassandra Keyspace. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current Cassandra Keyspace. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_update_cassandra_keyspace_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - update_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Cassandra Keyspace. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current Cassandra Keyspace. Required. - :type update_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_update_cassandra_keyspace_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Cassandra Keyspace. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current Cassandra Keyspace. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] - type. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._update_cassandra_keyspace_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - update_throughput_parameters=update_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _migrate_cassandra_keyspace_to_autoscale_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_cassandra_keyspace_to_autoscale_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_migrate_cassandra_keyspace_to_autoscale( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB Cassandra Keyspace from manual throughput to autoscale. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._migrate_cassandra_keyspace_to_autoscale_initial( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _migrate_cassandra_keyspace_to_manual_throughput_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_cassandra_keyspace_to_manual_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_migrate_cassandra_keyspace_to_manual_throughput( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB Cassandra Keyspace from autoscale to manual throughput. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._migrate_cassandra_keyspace_to_manual_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @distributed_trace - def list_cassandra_tables( - self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any - ) -> Iterable["_models.CassandraTableGetResults"]: - """Lists the Cassandra table under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :return: An iterator like instance of either CassandraTableGetResults or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.CassandraTableGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.CassandraTableListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_cassandra_tables_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("CassandraTableListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get_cassandra_table( - self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any - ) -> _models.CassandraTableGetResults: - """Gets the Cassandra table under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :return: CassandraTableGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.CassandraTableGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.CassandraTableGetResults] = kwargs.pop("cls", None) - - _request = build_get_cassandra_table_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - table_name=table_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("CassandraTableGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _create_update_cassandra_table_initial( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - table_name: str, - create_update_cassandra_table_parameters: Union[_models.CassandraTableCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_cassandra_table_parameters, (IOBase, bytes)): - _content = create_update_cassandra_table_parameters - else: - _json = self._serialize.body( - create_update_cassandra_table_parameters, "CassandraTableCreateUpdateParameters" - ) - - _request = build_create_update_cassandra_table_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - table_name=table_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_update_cassandra_table( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - table_name: str, - create_update_cassandra_table_parameters: _models.CassandraTableCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.CassandraTableGetResults]: - """Create or update an Azure Cosmos DB Cassandra Table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :param create_update_cassandra_table_parameters: The parameters to provide for the current - Cassandra Table. Required. - :type create_update_cassandra_table_parameters: - ~azure.mgmt.cosmosdb.models.CassandraTableCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either CassandraTableGetResults or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.CassandraTableGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_update_cassandra_table( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - table_name: str, - create_update_cassandra_table_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.CassandraTableGetResults]: - """Create or update an Azure Cosmos DB Cassandra Table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :param create_update_cassandra_table_parameters: The parameters to provide for the current - Cassandra Table. Required. - :type create_update_cassandra_table_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either CassandraTableGetResults or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.CassandraTableGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_update_cassandra_table( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - table_name: str, - create_update_cassandra_table_parameters: Union[_models.CassandraTableCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.CassandraTableGetResults]: - """Create or update an Azure Cosmos DB Cassandra Table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :param create_update_cassandra_table_parameters: The parameters to provide for the current - Cassandra Table. Is either a CassandraTableCreateUpdateParameters type or a IO[bytes] type. - Required. - :type create_update_cassandra_table_parameters: - ~azure.mgmt.cosmosdb.models.CassandraTableCreateUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either CassandraTableGetResults or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.CassandraTableGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.CassandraTableGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_update_cassandra_table_initial( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - table_name=table_name, - create_update_cassandra_table_parameters=create_update_cassandra_table_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("CassandraTableGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.CassandraTableGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.CassandraTableGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _delete_cassandra_table_initial( - self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_cassandra_table_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - table_name=table_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete_cassandra_table( - self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any - ) -> LROPoller[None]: - """Deletes an existing Azure Cosmos DB Cassandra table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_cassandra_table_initial( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - table_name=table_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace - def get_cassandra_table_throughput( - self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any - ) -> _models.ThroughputSettingsGetResults: - """Gets the RUs per second of the Cassandra table under an existing Azure Cosmos DB database - account with the provided name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :return: ThroughputSettingsGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - - _request = build_get_cassandra_table_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - table_name=table_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _update_cassandra_table_throughput_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - table_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(update_throughput_parameters, (IOBase, bytes)): - _content = update_throughput_parameters - else: - _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") - - _request = build_update_cassandra_table_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - table_name=table_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_update_cassandra_table_throughput( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - table_name: str, - update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Cassandra table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current Cassandra table. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_update_cassandra_table_throughput( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - table_name: str, - update_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Cassandra table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current Cassandra table. Required. - :type update_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_update_cassandra_table_throughput( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - table_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Cassandra table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current Cassandra table. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] - type. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._update_cassandra_table_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - table_name=table_name, - update_throughput_parameters=update_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _migrate_cassandra_table_to_autoscale_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_cassandra_table_to_autoscale_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - table_name=table_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_migrate_cassandra_table_to_autoscale( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB Cassandra table from manual throughput to autoscale. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._migrate_cassandra_table_to_autoscale_initial( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - table_name=table_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _migrate_cassandra_table_to_manual_throughput_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_cassandra_table_to_manual_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - table_name=table_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_migrate_cassandra_table_to_manual_throughput( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB Cassandra table from autoscale to manual throughput. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._migrate_cassandra_table_to_manual_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - table_name=table_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @distributed_trace - def list_cassandra_views( - self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any - ) -> Iterable["_models.CassandraViewGetResults"]: - """Lists the Cassandra materialized views under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :return: An iterator like instance of either CassandraViewGetResults or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.CassandraViewGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.CassandraViewListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_cassandra_views_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("CassandraViewListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get_cassandra_view( - self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any - ) -> _models.CassandraViewGetResults: - """Gets the Cassandra view under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param view_name: Cosmos DB view name. Required. - :type view_name: str - :return: CassandraViewGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.CassandraViewGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.CassandraViewGetResults] = kwargs.pop("cls", None) - - _request = build_get_cassandra_view_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - view_name=view_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("CassandraViewGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _create_update_cassandra_view_initial( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - view_name: str, - create_update_cassandra_view_parameters: Union[_models.CassandraViewCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_cassandra_view_parameters, (IOBase, bytes)): - _content = create_update_cassandra_view_parameters - else: - _json = self._serialize.body(create_update_cassandra_view_parameters, "CassandraViewCreateUpdateParameters") - - _request = build_create_update_cassandra_view_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - view_name=view_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_update_cassandra_view( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - view_name: str, - create_update_cassandra_view_parameters: _models.CassandraViewCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.CassandraViewGetResults]: - """Create or update an Azure Cosmos DB Cassandra View. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param view_name: Cosmos DB view name. Required. - :type view_name: str - :param create_update_cassandra_view_parameters: The parameters to provide for the current - Cassandra View. Required. - :type create_update_cassandra_view_parameters: - ~azure.mgmt.cosmosdb.models.CassandraViewCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either CassandraViewGetResults or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.CassandraViewGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_update_cassandra_view( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - view_name: str, - create_update_cassandra_view_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.CassandraViewGetResults]: - """Create or update an Azure Cosmos DB Cassandra View. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param view_name: Cosmos DB view name. Required. - :type view_name: str - :param create_update_cassandra_view_parameters: The parameters to provide for the current - Cassandra View. Required. - :type create_update_cassandra_view_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either CassandraViewGetResults or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.CassandraViewGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_update_cassandra_view( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - view_name: str, - create_update_cassandra_view_parameters: Union[_models.CassandraViewCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.CassandraViewGetResults]: - """Create or update an Azure Cosmos DB Cassandra View. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param view_name: Cosmos DB view name. Required. - :type view_name: str - :param create_update_cassandra_view_parameters: The parameters to provide for the current - Cassandra View. Is either a CassandraViewCreateUpdateParameters type or a IO[bytes] type. - Required. - :type create_update_cassandra_view_parameters: - ~azure.mgmt.cosmosdb.models.CassandraViewCreateUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either CassandraViewGetResults or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.CassandraViewGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.CassandraViewGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_update_cassandra_view_initial( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - view_name=view_name, - create_update_cassandra_view_parameters=create_update_cassandra_view_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("CassandraViewGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.CassandraViewGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.CassandraViewGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _delete_cassandra_view_initial( - self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_cassandra_view_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - view_name=view_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202, 204]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete_cassandra_view( - self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any - ) -> LROPoller[None]: - """Deletes an existing Azure Cosmos DB Cassandra view. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param view_name: Cosmos DB view name. Required. - :type view_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_cassandra_view_initial( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - view_name=view_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace - def get_cassandra_view_throughput( - self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any - ) -> _models.ThroughputSettingsGetResults: - """Gets the RUs per second of the Cassandra view under an existing Azure Cosmos DB database - account with the provided name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param view_name: Cosmos DB view name. Required. - :type view_name: str - :return: ThroughputSettingsGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - - _request = build_get_cassandra_view_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - view_name=view_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _update_cassandra_view_throughput_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - view_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(update_throughput_parameters, (IOBase, bytes)): - _content = update_throughput_parameters - else: - _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") - - _request = build_update_cassandra_view_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - view_name=view_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_update_cassandra_view_throughput( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - view_name: str, - update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Cassandra view. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param view_name: Cosmos DB view name. Required. - :type view_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current Cassandra view. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_update_cassandra_view_throughput( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - view_name: str, - update_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Cassandra view. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param view_name: Cosmos DB view name. Required. - :type view_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current Cassandra view. Required. - :type update_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_update_cassandra_view_throughput( - self, - resource_group_name: str, - account_name: str, - keyspace_name: str, - view_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Cassandra view. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param view_name: Cosmos DB view name. Required. - :type view_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current Cassandra view. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] - type. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._update_cassandra_view_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - view_name=view_name, - update_throughput_parameters=update_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _migrate_cassandra_view_to_autoscale_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_cassandra_view_to_autoscale_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - view_name=view_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_migrate_cassandra_view_to_autoscale( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB Cassandra view from manual throughput to autoscale. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param view_name: Cosmos DB view name. Required. - :type view_name: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._migrate_cassandra_view_to_autoscale_initial( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - view_name=view_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _migrate_cassandra_view_to_manual_throughput_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_cassandra_view_to_manual_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - view_name=view_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_migrate_cassandra_view_to_manual_throughput( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB Cassandra view from autoscale to manual throughput. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param keyspace_name: Cosmos DB keyspace name. Required. - :type keyspace_name: str - :param view_name: Cosmos DB view name. Required. - :type view_name: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._migrate_cassandra_view_to_manual_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - keyspace_name=keyspace_name, - view_name=view_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_cassandra_keyspaces_request( + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_cassandra_keyspace_request( + resource_group_name: str, account_name: str, keyspace_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_update_cassandra_keyspace_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, keyspace_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_cassandra_keyspace_request( + resource_group_name: str, account_name: str, keyspace_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_get_cassandra_keyspace_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, keyspace_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/throughputSettings/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_cassandra_keyspace_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, keyspace_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/throughputSettings/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_migrate_cassandra_keyspace_to_autoscale_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, keyspace_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/throughputSettings/default/migrateToAutoscale", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_migrate_cassandra_keyspace_to_manual_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, keyspace_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/throughputSettings/default/migrateToManualThroughput", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_cassandra_tables_request( + resource_group_name: str, account_name: str, keyspace_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/tables", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_cassandra_table_request( + resource_group_name: str, + account_name: str, + keyspace_name: str, + table_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/tables/{tableName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), + "tableName": _SERIALIZER.url("table_name", table_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_update_cassandra_table_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + keyspace_name: str, + table_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/tables/{tableName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), + "tableName": _SERIALIZER.url("table_name", table_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_cassandra_table_request( + resource_group_name: str, + account_name: str, + keyspace_name: str, + table_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/tables/{tableName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), + "tableName": _SERIALIZER.url("table_name", table_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_get_cassandra_table_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + keyspace_name: str, + table_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/tables/{tableName}/throughputSettings/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), + "tableName": _SERIALIZER.url("table_name", table_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_cassandra_table_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + keyspace_name: str, + table_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/tables/{tableName}/throughputSettings/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), + "tableName": _SERIALIZER.url("table_name", table_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_migrate_cassandra_table_to_autoscale_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + keyspace_name: str, + table_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/tables/{tableName}/throughputSettings/default/migrateToAutoscale", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), + "tableName": _SERIALIZER.url("table_name", table_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_migrate_cassandra_table_to_manual_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + keyspace_name: str, + table_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/tables/{tableName}/throughputSettings/default/migrateToManualThroughput", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), + "tableName": _SERIALIZER.url("table_name", table_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_cassandra_views_request( + resource_group_name: str, account_name: str, keyspace_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/views", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_cassandra_view_request( + resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/views/{viewName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), + "viewName": _SERIALIZER.url("view_name", view_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_update_cassandra_view_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/views/{viewName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), + "viewName": _SERIALIZER.url("view_name", view_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_cassandra_view_request( + resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/views/{viewName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), + "viewName": _SERIALIZER.url("view_name", view_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_get_cassandra_view_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/views/{viewName}/throughputSettings/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), + "viewName": _SERIALIZER.url("view_name", view_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_cassandra_view_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/views/{viewName}/throughputSettings/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), + "viewName": _SERIALIZER.url("view_name", view_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_migrate_cassandra_view_to_autoscale_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/views/{viewName}/throughputSettings/default/migrateToAutoscale", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), + "viewName": _SERIALIZER.url("view_name", view_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_migrate_cassandra_view_to_manual_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/cassandraKeyspaces/{keyspaceName}/views/{viewName}/throughputSettings/default/migrateToManualThroughput", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "keyspaceName": _SERIALIZER.url("keyspace_name", keyspace_name, "str"), + "viewName": _SERIALIZER.url("view_name", view_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class CassandraResourcesOperations: # pylint: disable=too-many-public-methods + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`cassandra_resources` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_cassandra_keyspaces( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> Iterable["_models.CassandraKeyspaceGetResults"]: + """Lists the Cassandra keyspaces under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either CassandraKeyspaceGetResults or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.CassandraKeyspaceGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.CassandraKeyspaceListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_cassandra_keyspaces_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("CassandraKeyspaceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get_cassandra_keyspace( + self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any + ) -> _models.CassandraKeyspaceGetResults: + """Gets the Cassandra keyspaces under an existing Azure Cosmos DB database account with the + provided name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :return: CassandraKeyspaceGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.CassandraKeyspaceGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.CassandraKeyspaceGetResults] = kwargs.pop("cls", None) + + _request = build_get_cassandra_keyspace_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("CassandraKeyspaceGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_update_cassandra_keyspace_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + create_update_cassandra_keyspace_parameters: Union[_models.CassandraKeyspaceCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_cassandra_keyspace_parameters, (IOBase, bytes)): + _content = create_update_cassandra_keyspace_parameters + else: + _json = self._serialize.body( + create_update_cassandra_keyspace_parameters, "CassandraKeyspaceCreateUpdateParameters" + ) + + _request = build_create_update_cassandra_keyspace_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_update_cassandra_keyspace( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + create_update_cassandra_keyspace_parameters: _models.CassandraKeyspaceCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.CassandraKeyspaceGetResults]: + """Create or update an Azure Cosmos DB Cassandra keyspace. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param create_update_cassandra_keyspace_parameters: The parameters to provide for the current + Cassandra keyspace. Required. + :type create_update_cassandra_keyspace_parameters: + ~azure.mgmt.cosmosdb.models.CassandraKeyspaceCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either CassandraKeyspaceGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.CassandraKeyspaceGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_update_cassandra_keyspace( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + create_update_cassandra_keyspace_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.CassandraKeyspaceGetResults]: + """Create or update an Azure Cosmos DB Cassandra keyspace. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param create_update_cassandra_keyspace_parameters: The parameters to provide for the current + Cassandra keyspace. Required. + :type create_update_cassandra_keyspace_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either CassandraKeyspaceGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.CassandraKeyspaceGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_update_cassandra_keyspace( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + create_update_cassandra_keyspace_parameters: Union[_models.CassandraKeyspaceCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.CassandraKeyspaceGetResults]: + """Create or update an Azure Cosmos DB Cassandra keyspace. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param create_update_cassandra_keyspace_parameters: The parameters to provide for the current + Cassandra keyspace. Is either a CassandraKeyspaceCreateUpdateParameters type or a IO[bytes] + type. Required. + :type create_update_cassandra_keyspace_parameters: + ~azure.mgmt.cosmosdb.models.CassandraKeyspaceCreateUpdateParameters or IO[bytes] + :return: An instance of LROPoller that returns either CassandraKeyspaceGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.CassandraKeyspaceGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CassandraKeyspaceGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_update_cassandra_keyspace_initial( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + create_update_cassandra_keyspace_parameters=create_update_cassandra_keyspace_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("CassandraKeyspaceGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.CassandraKeyspaceGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.CassandraKeyspaceGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_cassandra_keyspace_initial( + self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_cassandra_keyspace_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete_cassandra_keyspace( + self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Deletes an existing Azure Cosmos DB Cassandra keyspace. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_cassandra_keyspace_initial( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def get_cassandra_keyspace_throughput( + self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any + ) -> _models.ThroughputSettingsGetResults: + """Gets the RUs per second of the Cassandra Keyspace under an existing Azure Cosmos DB database + account with the provided name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :return: ThroughputSettingsGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + + _request = build_get_cassandra_keyspace_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _update_cassandra_keyspace_throughput_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(update_throughput_parameters, (IOBase, bytes)): + _content = update_throughput_parameters + else: + _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") + + _request = build_update_cassandra_keyspace_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_update_cassandra_keyspace_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Cassandra Keyspace. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current Cassandra Keyspace. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update_cassandra_keyspace_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + update_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Cassandra Keyspace. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current Cassandra Keyspace. Required. + :type update_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update_cassandra_keyspace_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Cassandra Keyspace. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current Cassandra Keyspace. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] + type. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._update_cassandra_keyspace_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + update_throughput_parameters=update_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _migrate_cassandra_keyspace_to_autoscale_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_cassandra_keyspace_to_autoscale_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_migrate_cassandra_keyspace_to_autoscale( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB Cassandra Keyspace from manual throughput to autoscale. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._migrate_cassandra_keyspace_to_autoscale_initial( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _migrate_cassandra_keyspace_to_manual_throughput_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_cassandra_keyspace_to_manual_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_migrate_cassandra_keyspace_to_manual_throughput( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB Cassandra Keyspace from autoscale to manual throughput. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._migrate_cassandra_keyspace_to_manual_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def list_cassandra_tables( + self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any + ) -> Iterable["_models.CassandraTableGetResults"]: + """Lists the Cassandra table under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :return: An iterator like instance of either CassandraTableGetResults or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.CassandraTableGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.CassandraTableListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_cassandra_tables_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("CassandraTableListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get_cassandra_table( + self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any + ) -> _models.CassandraTableGetResults: + """Gets the Cassandra table under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :return: CassandraTableGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.CassandraTableGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.CassandraTableGetResults] = kwargs.pop("cls", None) + + _request = build_get_cassandra_table_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + table_name=table_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("CassandraTableGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_update_cassandra_table_initial( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + table_name: str, + create_update_cassandra_table_parameters: Union[_models.CassandraTableCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_cassandra_table_parameters, (IOBase, bytes)): + _content = create_update_cassandra_table_parameters + else: + _json = self._serialize.body( + create_update_cassandra_table_parameters, "CassandraTableCreateUpdateParameters" + ) + + _request = build_create_update_cassandra_table_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + table_name=table_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_update_cassandra_table( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + table_name: str, + create_update_cassandra_table_parameters: _models.CassandraTableCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.CassandraTableGetResults]: + """Create or update an Azure Cosmos DB Cassandra Table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :param create_update_cassandra_table_parameters: The parameters to provide for the current + Cassandra Table. Required. + :type create_update_cassandra_table_parameters: + ~azure.mgmt.cosmosdb.models.CassandraTableCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either CassandraTableGetResults or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.CassandraTableGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_update_cassandra_table( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + table_name: str, + create_update_cassandra_table_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.CassandraTableGetResults]: + """Create or update an Azure Cosmos DB Cassandra Table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :param create_update_cassandra_table_parameters: The parameters to provide for the current + Cassandra Table. Required. + :type create_update_cassandra_table_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either CassandraTableGetResults or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.CassandraTableGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_update_cassandra_table( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + table_name: str, + create_update_cassandra_table_parameters: Union[_models.CassandraTableCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.CassandraTableGetResults]: + """Create or update an Azure Cosmos DB Cassandra Table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :param create_update_cassandra_table_parameters: The parameters to provide for the current + Cassandra Table. Is either a CassandraTableCreateUpdateParameters type or a IO[bytes] type. + Required. + :type create_update_cassandra_table_parameters: + ~azure.mgmt.cosmosdb.models.CassandraTableCreateUpdateParameters or IO[bytes] + :return: An instance of LROPoller that returns either CassandraTableGetResults or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.CassandraTableGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CassandraTableGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_update_cassandra_table_initial( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + table_name=table_name, + create_update_cassandra_table_parameters=create_update_cassandra_table_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("CassandraTableGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.CassandraTableGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.CassandraTableGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_cassandra_table_initial( + self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_cassandra_table_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + table_name=table_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete_cassandra_table( + self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Deletes an existing Azure Cosmos DB Cassandra table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_cassandra_table_initial( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + table_name=table_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def get_cassandra_table_throughput( + self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any + ) -> _models.ThroughputSettingsGetResults: + """Gets the RUs per second of the Cassandra table under an existing Azure Cosmos DB database + account with the provided name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :return: ThroughputSettingsGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + + _request = build_get_cassandra_table_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + table_name=table_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _update_cassandra_table_throughput_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + table_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(update_throughput_parameters, (IOBase, bytes)): + _content = update_throughput_parameters + else: + _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") + + _request = build_update_cassandra_table_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + table_name=table_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_update_cassandra_table_throughput( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + table_name: str, + update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Cassandra table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current Cassandra table. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update_cassandra_table_throughput( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + table_name: str, + update_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Cassandra table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current Cassandra table. Required. + :type update_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update_cassandra_table_throughput( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + table_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Cassandra table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current Cassandra table. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] + type. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._update_cassandra_table_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + table_name=table_name, + update_throughput_parameters=update_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _migrate_cassandra_table_to_autoscale_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_cassandra_table_to_autoscale_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + table_name=table_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_migrate_cassandra_table_to_autoscale( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB Cassandra table from manual throughput to autoscale. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._migrate_cassandra_table_to_autoscale_initial( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + table_name=table_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _migrate_cassandra_table_to_manual_throughput_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_cassandra_table_to_manual_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + table_name=table_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_migrate_cassandra_table_to_manual_throughput( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, keyspace_name: str, table_name: str, **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB Cassandra table from autoscale to manual throughput. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._migrate_cassandra_table_to_manual_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + table_name=table_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def list_cassandra_views( + self, resource_group_name: str, account_name: str, keyspace_name: str, **kwargs: Any + ) -> Iterable["_models.CassandraViewGetResults"]: + """Lists the Cassandra materialized views under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :return: An iterator like instance of either CassandraViewGetResults or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.CassandraViewGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.CassandraViewListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_cassandra_views_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("CassandraViewListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get_cassandra_view( + self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any + ) -> _models.CassandraViewGetResults: + """Gets the Cassandra view under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param view_name: Cosmos DB view name. Required. + :type view_name: str + :return: CassandraViewGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.CassandraViewGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.CassandraViewGetResults] = kwargs.pop("cls", None) + + _request = build_get_cassandra_view_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + view_name=view_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("CassandraViewGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_update_cassandra_view_initial( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + view_name: str, + create_update_cassandra_view_parameters: Union[_models.CassandraViewCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_cassandra_view_parameters, (IOBase, bytes)): + _content = create_update_cassandra_view_parameters + else: + _json = self._serialize.body(create_update_cassandra_view_parameters, "CassandraViewCreateUpdateParameters") + + _request = build_create_update_cassandra_view_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + view_name=view_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_update_cassandra_view( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + view_name: str, + create_update_cassandra_view_parameters: _models.CassandraViewCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.CassandraViewGetResults]: + """Create or update an Azure Cosmos DB Cassandra View. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param view_name: Cosmos DB view name. Required. + :type view_name: str + :param create_update_cassandra_view_parameters: The parameters to provide for the current + Cassandra View. Required. + :type create_update_cassandra_view_parameters: + ~azure.mgmt.cosmosdb.models.CassandraViewCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either CassandraViewGetResults or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.CassandraViewGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_update_cassandra_view( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + view_name: str, + create_update_cassandra_view_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.CassandraViewGetResults]: + """Create or update an Azure Cosmos DB Cassandra View. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param view_name: Cosmos DB view name. Required. + :type view_name: str + :param create_update_cassandra_view_parameters: The parameters to provide for the current + Cassandra View. Required. + :type create_update_cassandra_view_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either CassandraViewGetResults or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.CassandraViewGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_update_cassandra_view( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + view_name: str, + create_update_cassandra_view_parameters: Union[_models.CassandraViewCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.CassandraViewGetResults]: + """Create or update an Azure Cosmos DB Cassandra View. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param view_name: Cosmos DB view name. Required. + :type view_name: str + :param create_update_cassandra_view_parameters: The parameters to provide for the current + Cassandra View. Is either a CassandraViewCreateUpdateParameters type or a IO[bytes] type. + Required. + :type create_update_cassandra_view_parameters: + ~azure.mgmt.cosmosdb.models.CassandraViewCreateUpdateParameters or IO[bytes] + :return: An instance of LROPoller that returns either CassandraViewGetResults or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.CassandraViewGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CassandraViewGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_update_cassandra_view_initial( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + view_name=view_name, + create_update_cassandra_view_parameters=create_update_cassandra_view_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("CassandraViewGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.CassandraViewGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.CassandraViewGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_cassandra_view_initial( + self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_cassandra_view_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + view_name=view_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete_cassandra_view( + self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Deletes an existing Azure Cosmos DB Cassandra view. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param view_name: Cosmos DB view name. Required. + :type view_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_cassandra_view_initial( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + view_name=view_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def get_cassandra_view_throughput( + self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any + ) -> _models.ThroughputSettingsGetResults: + """Gets the RUs per second of the Cassandra view under an existing Azure Cosmos DB database + account with the provided name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param view_name: Cosmos DB view name. Required. + :type view_name: str + :return: ThroughputSettingsGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + + _request = build_get_cassandra_view_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + view_name=view_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _update_cassandra_view_throughput_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + view_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(update_throughput_parameters, (IOBase, bytes)): + _content = update_throughput_parameters + else: + _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") + + _request = build_update_cassandra_view_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + view_name=view_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_update_cassandra_view_throughput( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + view_name: str, + update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Cassandra view. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param view_name: Cosmos DB view name. Required. + :type view_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current Cassandra view. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update_cassandra_view_throughput( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + view_name: str, + update_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Cassandra view. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param view_name: Cosmos DB view name. Required. + :type view_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current Cassandra view. Required. + :type update_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update_cassandra_view_throughput( + self, + resource_group_name: str, + account_name: str, + keyspace_name: str, + view_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Cassandra view. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param view_name: Cosmos DB view name. Required. + :type view_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current Cassandra view. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] + type. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._update_cassandra_view_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + view_name=view_name, + update_throughput_parameters=update_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _migrate_cassandra_view_to_autoscale_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_cassandra_view_to_autoscale_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + view_name=view_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_migrate_cassandra_view_to_autoscale( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB Cassandra view from manual throughput to autoscale. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param view_name: Cosmos DB view name. Required. + :type view_name: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._migrate_cassandra_view_to_autoscale_initial( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + view_name=view_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _migrate_cassandra_view_to_manual_throughput_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_cassandra_view_to_manual_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + view_name=view_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_migrate_cassandra_view_to_manual_throughput( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, keyspace_name: str, view_name: str, **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB Cassandra view from autoscale to manual throughput. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param keyspace_name: Cosmos DB keyspace name. Required. + :type keyspace_name: str + :param view_name: Cosmos DB view name. Required. + :type view_name: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._migrate_cassandra_view_to_manual_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + keyspace_name=keyspace_name, + view_name=view_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_chaos_fault_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_chaos_fault_operations.py index 38916ccbe3d..7cc4b3af386 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_chaos_fault_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_chaos_fault_operations.py @@ -1,524 +1,524 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.arm_polling import ARMPolling - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_request(resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/chaosFaults", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_enable_disable_request( - resource_group_name: str, account_name: str, chaos_fault: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/chaosFaults/{chaosFault}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "chaosFault": _SERIALIZER.url("chaos_fault", chaos_fault, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request( - resource_group_name: str, account_name: str, chaos_fault: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/chaosFaults/{chaosFault}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "chaosFault": _SERIALIZER.url("chaos_fault", chaos_fault, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class ChaosFaultOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`chaos_fault` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> Iterable["_models.ChaosFaultResource"]: - """List Chaos Faults for CosmosDB account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either ChaosFaultResource or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.ChaosFaultResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ChaosFaultListResponse] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("ChaosFaultListResponse", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - def _enable_disable_initial( - self, - resource_group_name: str, - account_name: str, - chaos_fault: str, - chaos_fault_request: Union[_models.ChaosFaultResource, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(chaos_fault_request, (IOBase, bytes)): - _content = chaos_fault_request - else: - _json = self._serialize.body(chaos_fault_request, "ChaosFaultResource") - - _request = build_enable_disable_request( - resource_group_name=resource_group_name, - account_name=account_name, - chaos_fault=chaos_fault, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_enable_disable( - self, - resource_group_name: str, - account_name: str, - chaos_fault: str, - chaos_fault_request: _models.ChaosFaultResource, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ChaosFaultResource]: - """Enable, disable Chaos Fault in a CosmosDB account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param chaos_fault: The name of the ChaosFault. Required. - :type chaos_fault: str - :param chaos_fault_request: A request object to enable/disable the chaos fault. Required. - :type chaos_fault_request: ~azure.mgmt.cosmosdb.models.ChaosFaultResource - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ChaosFaultResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ChaosFaultResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_enable_disable( - self, - resource_group_name: str, - account_name: str, - chaos_fault: str, - chaos_fault_request: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ChaosFaultResource]: - """Enable, disable Chaos Fault in a CosmosDB account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param chaos_fault: The name of the ChaosFault. Required. - :type chaos_fault: str - :param chaos_fault_request: A request object to enable/disable the chaos fault. Required. - :type chaos_fault_request: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ChaosFaultResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ChaosFaultResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_enable_disable( - self, - resource_group_name: str, - account_name: str, - chaos_fault: str, - chaos_fault_request: Union[_models.ChaosFaultResource, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.ChaosFaultResource]: - """Enable, disable Chaos Fault in a CosmosDB account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param chaos_fault: The name of the ChaosFault. Required. - :type chaos_fault: str - :param chaos_fault_request: A request object to enable/disable the chaos fault. Is either a - ChaosFaultResource type or a IO[bytes] type. Required. - :type chaos_fault_request: ~azure.mgmt.cosmosdb.models.ChaosFaultResource or IO[bytes] - :return: An instance of LROPoller that returns either ChaosFaultResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ChaosFaultResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ChaosFaultResource] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._enable_disable_initial( - resource_group_name=resource_group_name, - account_name=account_name, - chaos_fault=chaos_fault, - chaos_fault_request=chaos_fault_request, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ChaosFaultResource", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ChaosFaultResource].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ChaosFaultResource]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @distributed_trace - def get( - self, resource_group_name: str, account_name: str, chaos_fault: str, **kwargs: Any - ) -> _models.ChaosFaultResource: - """Get Chaos Fault for a CosmosdB account for a particular Chaos Fault. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param chaos_fault: The name of the ChaosFault. Required. - :type chaos_fault: str - :return: ChaosFaultResource or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ChaosFaultResource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ChaosFaultResource] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - account_name=account_name, - chaos_fault=chaos_fault, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ChaosFaultResource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/chaosFaults", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_enable_disable_request( + resource_group_name: str, account_name: str, chaos_fault: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/chaosFaults/{chaosFault}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "chaosFault": _SERIALIZER.url("chaos_fault", chaos_fault, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request( + resource_group_name: str, account_name: str, chaos_fault: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/chaosFaults/{chaosFault}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "chaosFault": _SERIALIZER.url("chaos_fault", chaos_fault, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class ChaosFaultOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`chaos_fault` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> Iterable["_models.ChaosFaultResource"]: + """List Chaos Faults for CosmosDB account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either ChaosFaultResource or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.ChaosFaultResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ChaosFaultListResponse] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ChaosFaultListResponse", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + def _enable_disable_initial( + self, + resource_group_name: str, + account_name: str, + chaos_fault: str, + chaos_fault_request: Union[_models.ChaosFaultResource, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(chaos_fault_request, (IOBase, bytes)): + _content = chaos_fault_request + else: + _json = self._serialize.body(chaos_fault_request, "ChaosFaultResource") + + _request = build_enable_disable_request( + resource_group_name=resource_group_name, + account_name=account_name, + chaos_fault=chaos_fault, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_enable_disable( + self, + resource_group_name: str, + account_name: str, + chaos_fault: str, + chaos_fault_request: _models.ChaosFaultResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ChaosFaultResource]: + """Enable, disable Chaos Fault in a CosmosDB account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param chaos_fault: The name of the ChaosFault. Required. + :type chaos_fault: str + :param chaos_fault_request: A request object to enable/disable the chaos fault. Required. + :type chaos_fault_request: ~azure.mgmt.cosmosdb.models.ChaosFaultResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ChaosFaultResource or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ChaosFaultResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_enable_disable( + self, + resource_group_name: str, + account_name: str, + chaos_fault: str, + chaos_fault_request: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ChaosFaultResource]: + """Enable, disable Chaos Fault in a CosmosDB account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param chaos_fault: The name of the ChaosFault. Required. + :type chaos_fault: str + :param chaos_fault_request: A request object to enable/disable the chaos fault. Required. + :type chaos_fault_request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ChaosFaultResource or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ChaosFaultResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_enable_disable( + self, + resource_group_name: str, + account_name: str, + chaos_fault: str, + chaos_fault_request: Union[_models.ChaosFaultResource, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.ChaosFaultResource]: + """Enable, disable Chaos Fault in a CosmosDB account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param chaos_fault: The name of the ChaosFault. Required. + :type chaos_fault: str + :param chaos_fault_request: A request object to enable/disable the chaos fault. Is either a + ChaosFaultResource type or a IO[bytes] type. Required. + :type chaos_fault_request: ~azure.mgmt.cosmosdb.models.ChaosFaultResource or IO[bytes] + :return: An instance of LROPoller that returns either ChaosFaultResource or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ChaosFaultResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ChaosFaultResource] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._enable_disable_initial( + resource_group_name=resource_group_name, + account_name=account_name, + chaos_fault=chaos_fault, + chaos_fault_request=chaos_fault_request, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ChaosFaultResource", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ChaosFaultResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ChaosFaultResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def get( + self, resource_group_name: str, account_name: str, chaos_fault: str, **kwargs: Any + ) -> _models.ChaosFaultResource: + """Get Chaos Fault for a CosmosdB account for a particular Chaos Fault. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param chaos_fault: The name of the ChaosFault. Required. + :type chaos_fault: str + :return: ChaosFaultResource or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ChaosFaultResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ChaosFaultResource] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + account_name=account_name, + chaos_fault=chaos_fault, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ChaosFaultResource", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_collection_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_collection_operations.py index 1efa58cbae4..a9c84bb0507 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_collection_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_collection_operations.py @@ -1,482 +1,482 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_metrics_request( - resource_group_name: str, - account_name: str, - database_rid: str, - collection_rid: str, - subscription_id: str, - *, - filter: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/databases/{databaseRid}/collections/{collectionRid}/metrics", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseRid": _SERIALIZER.url("database_rid", database_rid, "str"), - "collectionRid": _SERIALIZER.url("collection_rid", collection_rid, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_usages_request( - resource_group_name: str, - account_name: str, - database_rid: str, - collection_rid: str, - subscription_id: str, - *, - filter: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/databases/{databaseRid}/collections/{collectionRid}/usages", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseRid": _SERIALIZER.url("database_rid", database_rid, "str"), - "collectionRid": _SERIALIZER.url("collection_rid", collection_rid, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_metric_definitions_request( - resource_group_name: str, - account_name: str, - database_rid: str, - collection_rid: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/databases/{databaseRid}/collections/{collectionRid}/metricDefinitions", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseRid": _SERIALIZER.url("database_rid", database_rid, "str"), - "collectionRid": _SERIALIZER.url("collection_rid", collection_rid, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class CollectionOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`collection` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_metrics( - self, - resource_group_name: str, - account_name: str, - database_rid: str, - collection_rid: str, - filter: str, - **kwargs: Any - ) -> Iterable["_models.Metric"]: - """Retrieves the metrics determined by the given filter for the given database account and - collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_rid: Cosmos DB database rid. Required. - :type database_rid: str - :param collection_rid: Cosmos DB collection rid. Required. - :type collection_rid: str - :param filter: An OData filter expression that describes a subset of metrics to return. The - parameters that can be filtered are name.value (name of the metric, can have an or of multiple - names), startTime, endTime, and timeGrain. The supported operator is eq. Required. - :type filter: str - :return: An iterator like instance of either Metric or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.Metric] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MetricListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_metrics_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_rid=database_rid, - collection_rid=collection_rid, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("MetricListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list_usages( - self, - resource_group_name: str, - account_name: str, - database_rid: str, - collection_rid: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> Iterable["_models.Usage"]: - """Retrieves the usages (most recent storage data) for the given collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_rid: Cosmos DB database rid. Required. - :type database_rid: str - :param collection_rid: Cosmos DB collection rid. Required. - :type collection_rid: str - :param filter: An OData filter expression that describes a subset of usages to return. The - supported parameter is name.value (name of the metric, can have an or of multiple names). - Default value is None. - :type filter: str - :return: An iterator like instance of either Usage or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.Usage] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.UsagesResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_usages_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_rid=database_rid, - collection_rid=collection_rid, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("UsagesResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list_metric_definitions( - self, resource_group_name: str, account_name: str, database_rid: str, collection_rid: str, **kwargs: Any - ) -> Iterable["_models.MetricDefinition"]: - """Retrieves metric definitions for the given collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_rid: Cosmos DB database rid. Required. - :type database_rid: str - :param collection_rid: Cosmos DB collection rid. Required. - :type collection_rid: str - :return: An iterator like instance of either MetricDefinition or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.MetricDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MetricDefinitionsListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_metric_definitions_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_rid=database_rid, - collection_rid=collection_rid, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("MetricDefinitionsListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_metrics_request( + resource_group_name: str, + account_name: str, + database_rid: str, + collection_rid: str, + subscription_id: str, + *, + filter: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/databases/{databaseRid}/collections/{collectionRid}/metrics", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseRid": _SERIALIZER.url("database_rid", database_rid, "str"), + "collectionRid": _SERIALIZER.url("collection_rid", collection_rid, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_usages_request( + resource_group_name: str, + account_name: str, + database_rid: str, + collection_rid: str, + subscription_id: str, + *, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/databases/{databaseRid}/collections/{collectionRid}/usages", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseRid": _SERIALIZER.url("database_rid", database_rid, "str"), + "collectionRid": _SERIALIZER.url("collection_rid", collection_rid, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_metric_definitions_request( + resource_group_name: str, + account_name: str, + database_rid: str, + collection_rid: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/databases/{databaseRid}/collections/{collectionRid}/metricDefinitions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseRid": _SERIALIZER.url("database_rid", database_rid, "str"), + "collectionRid": _SERIALIZER.url("collection_rid", collection_rid, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class CollectionOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`collection` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_metrics( + self, + resource_group_name: str, + account_name: str, + database_rid: str, + collection_rid: str, + filter: str, + **kwargs: Any + ) -> Iterable["_models.Metric"]: + """Retrieves the metrics determined by the given filter for the given database account and + collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_rid: Cosmos DB database rid. Required. + :type database_rid: str + :param collection_rid: Cosmos DB collection rid. Required. + :type collection_rid: str + :param filter: An OData filter expression that describes a subset of metrics to return. The + parameters that can be filtered are name.value (name of the metric, can have an or of multiple + names), startTime, endTime, and timeGrain. The supported operator is eq. Required. + :type filter: str + :return: An iterator like instance of either Metric or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.Metric] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MetricListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_metrics_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_rid=database_rid, + collection_rid=collection_rid, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("MetricListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_usages( + self, + resource_group_name: str, + account_name: str, + database_rid: str, + collection_rid: str, + filter: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.Usage"]: + """Retrieves the usages (most recent storage data) for the given collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_rid: Cosmos DB database rid. Required. + :type database_rid: str + :param collection_rid: Cosmos DB collection rid. Required. + :type collection_rid: str + :param filter: An OData filter expression that describes a subset of usages to return. The + supported parameter is name.value (name of the metric, can have an or of multiple names). + Default value is None. + :type filter: str + :return: An iterator like instance of either Usage or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.Usage] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.UsagesResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_usages_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_rid=database_rid, + collection_rid=collection_rid, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("UsagesResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_metric_definitions( + self, resource_group_name: str, account_name: str, database_rid: str, collection_rid: str, **kwargs: Any + ) -> Iterable["_models.MetricDefinition"]: + """Retrieves metric definitions for the given collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_rid: Cosmos DB database rid. Required. + :type database_rid: str + :param collection_rid: Cosmos DB collection rid. Required. + :type collection_rid: str + :return: An iterator like instance of either MetricDefinition or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.MetricDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MetricDefinitionsListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_metric_definitions_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_rid=database_rid, + collection_rid=collection_rid, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("MetricDefinitionsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_collection_partition_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_collection_partition_operations.py index 2e5c4e677a3..a58d29c5792 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_collection_partition_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_collection_partition_operations.py @@ -1,351 +1,351 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_metrics_request( - resource_group_name: str, - account_name: str, - database_rid: str, - collection_rid: str, - subscription_id: str, - *, - filter: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/databases/{databaseRid}/collections/{collectionRid}/partitions/metrics", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseRid": _SERIALIZER.url("database_rid", database_rid, "str"), - "collectionRid": _SERIALIZER.url("collection_rid", collection_rid, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_usages_request( - resource_group_name: str, - account_name: str, - database_rid: str, - collection_rid: str, - subscription_id: str, - *, - filter: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/databases/{databaseRid}/collections/{collectionRid}/partitions/usages", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseRid": _SERIALIZER.url("database_rid", database_rid, "str"), - "collectionRid": _SERIALIZER.url("collection_rid", collection_rid, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class CollectionPartitionOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`collection_partition` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_metrics( - self, - resource_group_name: str, - account_name: str, - database_rid: str, - collection_rid: str, - filter: str, - **kwargs: Any - ) -> Iterable["_models.PartitionMetric"]: - """Retrieves the metrics determined by the given filter for the given collection, split by - partition. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_rid: Cosmos DB database rid. Required. - :type database_rid: str - :param collection_rid: Cosmos DB collection rid. Required. - :type collection_rid: str - :param filter: An OData filter expression that describes a subset of metrics to return. The - parameters that can be filtered are name.value (name of the metric, can have an or of multiple - names), startTime, endTime, and timeGrain. The supported operator is eq. Required. - :type filter: str - :return: An iterator like instance of either PartitionMetric or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.PartitionMetric] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.PartitionMetricListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_metrics_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_rid=database_rid, - collection_rid=collection_rid, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PartitionMetricListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list_usages( - self, - resource_group_name: str, - account_name: str, - database_rid: str, - collection_rid: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> Iterable["_models.PartitionUsage"]: - """Retrieves the usages (most recent storage data) for the given collection, split by partition. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_rid: Cosmos DB database rid. Required. - :type database_rid: str - :param collection_rid: Cosmos DB collection rid. Required. - :type collection_rid: str - :param filter: An OData filter expression that describes a subset of usages to return. The - supported parameter is name.value (name of the metric, can have an or of multiple names). - Default value is None. - :type filter: str - :return: An iterator like instance of either PartitionUsage or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.PartitionUsage] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.PartitionUsagesResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_usages_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_rid=database_rid, - collection_rid=collection_rid, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PartitionUsagesResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_metrics_request( + resource_group_name: str, + account_name: str, + database_rid: str, + collection_rid: str, + subscription_id: str, + *, + filter: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/databases/{databaseRid}/collections/{collectionRid}/partitions/metrics", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseRid": _SERIALIZER.url("database_rid", database_rid, "str"), + "collectionRid": _SERIALIZER.url("collection_rid", collection_rid, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_usages_request( + resource_group_name: str, + account_name: str, + database_rid: str, + collection_rid: str, + subscription_id: str, + *, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/databases/{databaseRid}/collections/{collectionRid}/partitions/usages", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseRid": _SERIALIZER.url("database_rid", database_rid, "str"), + "collectionRid": _SERIALIZER.url("collection_rid", collection_rid, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class CollectionPartitionOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`collection_partition` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_metrics( + self, + resource_group_name: str, + account_name: str, + database_rid: str, + collection_rid: str, + filter: str, + **kwargs: Any + ) -> Iterable["_models.PartitionMetric"]: + """Retrieves the metrics determined by the given filter for the given collection, split by + partition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_rid: Cosmos DB database rid. Required. + :type database_rid: str + :param collection_rid: Cosmos DB collection rid. Required. + :type collection_rid: str + :param filter: An OData filter expression that describes a subset of metrics to return. The + parameters that can be filtered are name.value (name of the metric, can have an or of multiple + names), startTime, endTime, and timeGrain. The supported operator is eq. Required. + :type filter: str + :return: An iterator like instance of either PartitionMetric or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.PartitionMetric] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PartitionMetricListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_metrics_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_rid=database_rid, + collection_rid=collection_rid, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PartitionMetricListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_usages( + self, + resource_group_name: str, + account_name: str, + database_rid: str, + collection_rid: str, + filter: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.PartitionUsage"]: + """Retrieves the usages (most recent storage data) for the given collection, split by partition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_rid: Cosmos DB database rid. Required. + :type database_rid: str + :param collection_rid: Cosmos DB collection rid. Required. + :type collection_rid: str + :param filter: An OData filter expression that describes a subset of usages to return. The + supported parameter is name.value (name of the metric, can have an or of multiple names). + Default value is None. + :type filter: str + :return: An iterator like instance of either PartitionUsage or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.PartitionUsage] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PartitionUsagesResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_usages_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_rid=database_rid, + collection_rid=collection_rid, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PartitionUsagesResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_collection_partition_region_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_collection_partition_region_operations.py index 7f49e1da693..f8e54a81f95 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_collection_partition_region_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_collection_partition_region_operations.py @@ -1,211 +1,211 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_metrics_request( - resource_group_name: str, - account_name: str, - region: str, - database_rid: str, - collection_rid: str, - subscription_id: str, - *, - filter: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/region/{region}/databases/{databaseRid}/collections/{collectionRid}/partitions/metrics", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "region": _SERIALIZER.url("region", region, "str"), - "databaseRid": _SERIALIZER.url("database_rid", database_rid, "str"), - "collectionRid": _SERIALIZER.url("collection_rid", collection_rid, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class CollectionPartitionRegionOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`collection_partition_region` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_metrics( - self, - resource_group_name: str, - account_name: str, - region: str, - database_rid: str, - collection_rid: str, - filter: str, - **kwargs: Any - ) -> Iterable["_models.PartitionMetric"]: - """Retrieves the metrics determined by the given filter for the given collection and region, split - by partition. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param region: Cosmos DB region, with spaces between words and each word capitalized. Required. - :type region: str - :param database_rid: Cosmos DB database rid. Required. - :type database_rid: str - :param collection_rid: Cosmos DB collection rid. Required. - :type collection_rid: str - :param filter: An OData filter expression that describes a subset of metrics to return. The - parameters that can be filtered are name.value (name of the metric, can have an or of multiple - names), startTime, endTime, and timeGrain. The supported operator is eq. Required. - :type filter: str - :return: An iterator like instance of either PartitionMetric or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.PartitionMetric] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.PartitionMetricListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_metrics_request( - resource_group_name=resource_group_name, - account_name=account_name, - region=region, - database_rid=database_rid, - collection_rid=collection_rid, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PartitionMetricListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_metrics_request( + resource_group_name: str, + account_name: str, + region: str, + database_rid: str, + collection_rid: str, + subscription_id: str, + *, + filter: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/region/{region}/databases/{databaseRid}/collections/{collectionRid}/partitions/metrics", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "region": _SERIALIZER.url("region", region, "str"), + "databaseRid": _SERIALIZER.url("database_rid", database_rid, "str"), + "collectionRid": _SERIALIZER.url("collection_rid", collection_rid, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class CollectionPartitionRegionOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`collection_partition_region` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_metrics( + self, + resource_group_name: str, + account_name: str, + region: str, + database_rid: str, + collection_rid: str, + filter: str, + **kwargs: Any + ) -> Iterable["_models.PartitionMetric"]: + """Retrieves the metrics determined by the given filter for the given collection and region, split + by partition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param region: Cosmos DB region, with spaces between words and each word capitalized. Required. + :type region: str + :param database_rid: Cosmos DB database rid. Required. + :type database_rid: str + :param collection_rid: Cosmos DB collection rid. Required. + :type collection_rid: str + :param filter: An OData filter expression that describes a subset of metrics to return. The + parameters that can be filtered are name.value (name of the metric, can have an or of multiple + names), startTime, endTime, and timeGrain. The supported operator is eq. Required. + :type filter: str + :return: An iterator like instance of either PartitionMetric or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.PartitionMetric] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PartitionMetricListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_metrics_request( + resource_group_name=resource_group_name, + account_name=account_name, + region=region, + database_rid=database_rid, + collection_rid=collection_rid, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PartitionMetricListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_collection_region_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_collection_region_operations.py index 63f487ea8ed..43c05977b7f 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_collection_region_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_collection_region_operations.py @@ -1,211 +1,211 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_metrics_request( - resource_group_name: str, - account_name: str, - region: str, - database_rid: str, - collection_rid: str, - subscription_id: str, - *, - filter: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/region/{region}/databases/{databaseRid}/collections/{collectionRid}/metrics", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "region": _SERIALIZER.url("region", region, "str"), - "databaseRid": _SERIALIZER.url("database_rid", database_rid, "str"), - "collectionRid": _SERIALIZER.url("collection_rid", collection_rid, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class CollectionRegionOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`collection_region` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_metrics( - self, - resource_group_name: str, - account_name: str, - region: str, - database_rid: str, - collection_rid: str, - filter: str, - **kwargs: Any - ) -> Iterable["_models.Metric"]: - """Retrieves the metrics determined by the given filter for the given database account, collection - and region. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param region: Cosmos DB region, with spaces between words and each word capitalized. Required. - :type region: str - :param database_rid: Cosmos DB database rid. Required. - :type database_rid: str - :param collection_rid: Cosmos DB collection rid. Required. - :type collection_rid: str - :param filter: An OData filter expression that describes a subset of metrics to return. The - parameters that can be filtered are name.value (name of the metric, can have an or of multiple - names), startTime, endTime, and timeGrain. The supported operator is eq. Required. - :type filter: str - :return: An iterator like instance of either Metric or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.Metric] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MetricListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_metrics_request( - resource_group_name=resource_group_name, - account_name=account_name, - region=region, - database_rid=database_rid, - collection_rid=collection_rid, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("MetricListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_metrics_request( + resource_group_name: str, + account_name: str, + region: str, + database_rid: str, + collection_rid: str, + subscription_id: str, + *, + filter: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/region/{region}/databases/{databaseRid}/collections/{collectionRid}/metrics", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "region": _SERIALIZER.url("region", region, "str"), + "databaseRid": _SERIALIZER.url("database_rid", database_rid, "str"), + "collectionRid": _SERIALIZER.url("collection_rid", collection_rid, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class CollectionRegionOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`collection_region` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_metrics( + self, + resource_group_name: str, + account_name: str, + region: str, + database_rid: str, + collection_rid: str, + filter: str, + **kwargs: Any + ) -> Iterable["_models.Metric"]: + """Retrieves the metrics determined by the given filter for the given database account, collection + and region. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param region: Cosmos DB region, with spaces between words and each word capitalized. Required. + :type region: str + :param database_rid: Cosmos DB database rid. Required. + :type database_rid: str + :param collection_rid: Cosmos DB collection rid. Required. + :type collection_rid: str + :param filter: An OData filter expression that describes a subset of metrics to return. The + parameters that can be filtered are name.value (name of the metric, can have an or of multiple + names), startTime, endTime, and timeGrain. The supported operator is eq. Required. + :type filter: str + :return: An iterator like instance of either Metric or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.Metric] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MetricListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_metrics_request( + resource_group_name=resource_group_name, + account_name=account_name, + region=region, + database_rid=database_rid, + collection_rid=collection_rid, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("MetricListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_data_transfer_jobs_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_data_transfer_jobs_operations.py index 049c23b7e11..8ae381b21c4 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_data_transfer_jobs_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_data_transfer_jobs_operations.py @@ -1,837 +1,837 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Iterable, Optional, Type, TypeVar, Union, overload -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_create_request( - resource_group_name: str, account_name: str, job_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/dataTransferJobs/{jobName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "jobName": _SERIALIZER.url("job_name", job_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request( - resource_group_name: str, account_name: str, job_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/dataTransferJobs/{jobName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "jobName": _SERIALIZER.url("job_name", job_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_pause_request( - resource_group_name: str, account_name: str, job_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/dataTransferJobs/{jobName}/pause", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "jobName": _SERIALIZER.url("job_name", job_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_resume_request( - resource_group_name: str, account_name: str, job_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/dataTransferJobs/{jobName}/resume", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "jobName": _SERIALIZER.url("job_name", job_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_cancel_request( - resource_group_name: str, account_name: str, job_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/dataTransferJobs/{jobName}/cancel", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "jobName": _SERIALIZER.url("job_name", job_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_complete_request( - resource_group_name: str, account_name: str, job_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/dataTransferJobs/{jobName}/complete", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "jobName": _SERIALIZER.url("job_name", job_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_by_database_account_request( - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/dataTransferJobs", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class DataTransferJobsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`data_transfer_jobs` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - def create( - self, - resource_group_name: str, - account_name: str, - job_name: str, - job_create_parameters: _models.CreateJobRequest, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.DataTransferJobGetResults: - """Creates a Data Transfer Job. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param job_name: Name of the Data Transfer Job. Required. - :type job_name: str - :param job_create_parameters: Required. - :type job_create_parameters: ~azure.mgmt.cosmosdb.models.CreateJobRequest - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: DataTransferJobGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create( - self, - resource_group_name: str, - account_name: str, - job_name: str, - job_create_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.DataTransferJobGetResults: - """Creates a Data Transfer Job. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param job_name: Name of the Data Transfer Job. Required. - :type job_name: str - :param job_create_parameters: Required. - :type job_create_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: DataTransferJobGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create( - self, - resource_group_name: str, - account_name: str, - job_name: str, - job_create_parameters: Union[_models.CreateJobRequest, IO[bytes]], - **kwargs: Any - ) -> _models.DataTransferJobGetResults: - """Creates a Data Transfer Job. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param job_name: Name of the Data Transfer Job. Required. - :type job_name: str - :param job_create_parameters: Is either a CreateJobRequest type or a IO[bytes] type. Required. - :type job_create_parameters: ~azure.mgmt.cosmosdb.models.CreateJobRequest or IO[bytes] - :return: DataTransferJobGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.DataTransferJobGetResults] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(job_create_parameters, (IOBase, bytes)): - _content = job_create_parameters - else: - _json = self._serialize.body(job_create_parameters, "CreateJobRequest") - - _request = build_create_request( - resource_group_name=resource_group_name, - account_name=account_name, - job_name=job_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DataTransferJobGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get( - self, resource_group_name: str, account_name: str, job_name: str, **kwargs: Any - ) -> _models.DataTransferJobGetResults: - """Get a Data Transfer Job. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param job_name: Name of the Data Transfer Job. Required. - :type job_name: str - :return: DataTransferJobGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DataTransferJobGetResults] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - account_name=account_name, - job_name=job_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DataTransferJobGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def pause( - self, resource_group_name: str, account_name: str, job_name: str, **kwargs: Any - ) -> _models.DataTransferJobGetResults: - """Pause a Data Transfer Job. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param job_name: Name of the Data Transfer Job. Required. - :type job_name: str - :return: DataTransferJobGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DataTransferJobGetResults] = kwargs.pop("cls", None) - - _request = build_pause_request( - resource_group_name=resource_group_name, - account_name=account_name, - job_name=job_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DataTransferJobGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def resume( - self, resource_group_name: str, account_name: str, job_name: str, **kwargs: Any - ) -> _models.DataTransferJobGetResults: - """Resumes a Data Transfer Job. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param job_name: Name of the Data Transfer Job. Required. - :type job_name: str - :return: DataTransferJobGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DataTransferJobGetResults] = kwargs.pop("cls", None) - - _request = build_resume_request( - resource_group_name=resource_group_name, - account_name=account_name, - job_name=job_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DataTransferJobGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def cancel( - self, resource_group_name: str, account_name: str, job_name: str, **kwargs: Any - ) -> _models.DataTransferJobGetResults: - """Cancels a Data Transfer Job. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param job_name: Name of the Data Transfer Job. Required. - :type job_name: str - :return: DataTransferJobGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DataTransferJobGetResults] = kwargs.pop("cls", None) - - _request = build_cancel_request( - resource_group_name=resource_group_name, - account_name=account_name, - job_name=job_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DataTransferJobGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def complete( - self, resource_group_name: str, account_name: str, job_name: str, **kwargs: Any - ) -> _models.DataTransferJobGetResults: - """Completes a Data Transfer Online Job. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param job_name: Name of the Data Transfer Job. Required. - :type job_name: str - :return: DataTransferJobGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DataTransferJobGetResults] = kwargs.pop("cls", None) - - _request = build_complete_request( - resource_group_name=resource_group_name, - account_name=account_name, - job_name=job_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DataTransferJobGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_by_database_account( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> Iterable["_models.DataTransferJobGetResults"]: - """Get a list of Data Transfer jobs. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either DataTransferJobGetResults or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.DataTransferJobGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DataTransferJobFeedResults] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_by_database_account_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("DataTransferJobFeedResults", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, Type, TypeVar, Union, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_create_request( + resource_group_name: str, account_name: str, job_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/dataTransferJobs/{jobName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "jobName": _SERIALIZER.url("job_name", job_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request( + resource_group_name: str, account_name: str, job_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/dataTransferJobs/{jobName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "jobName": _SERIALIZER.url("job_name", job_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_pause_request( + resource_group_name: str, account_name: str, job_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/dataTransferJobs/{jobName}/pause", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "jobName": _SERIALIZER.url("job_name", job_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_resume_request( + resource_group_name: str, account_name: str, job_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/dataTransferJobs/{jobName}/resume", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "jobName": _SERIALIZER.url("job_name", job_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_cancel_request( + resource_group_name: str, account_name: str, job_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/dataTransferJobs/{jobName}/cancel", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "jobName": _SERIALIZER.url("job_name", job_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_complete_request( + resource_group_name: str, account_name: str, job_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/dataTransferJobs/{jobName}/complete", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "jobName": _SERIALIZER.url("job_name", job_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_database_account_request( + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/dataTransferJobs", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class DataTransferJobsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`data_transfer_jobs` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def create( + self, + resource_group_name: str, + account_name: str, + job_name: str, + job_create_parameters: _models.CreateJobRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.DataTransferJobGetResults: + """Creates a Data Transfer Job. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param job_name: Name of the Data Transfer Job. Required. + :type job_name: str + :param job_create_parameters: Required. + :type job_create_parameters: ~azure.mgmt.cosmosdb.models.CreateJobRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: DataTransferJobGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, + resource_group_name: str, + account_name: str, + job_name: str, + job_create_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.DataTransferJobGetResults: + """Creates a Data Transfer Job. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param job_name: Name of the Data Transfer Job. Required. + :type job_name: str + :param job_create_parameters: Required. + :type job_create_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: DataTransferJobGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create( + self, + resource_group_name: str, + account_name: str, + job_name: str, + job_create_parameters: Union[_models.CreateJobRequest, IO[bytes]], + **kwargs: Any + ) -> _models.DataTransferJobGetResults: + """Creates a Data Transfer Job. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param job_name: Name of the Data Transfer Job. Required. + :type job_name: str + :param job_create_parameters: Is either a CreateJobRequest type or a IO[bytes] type. Required. + :type job_create_parameters: ~azure.mgmt.cosmosdb.models.CreateJobRequest or IO[bytes] + :return: DataTransferJobGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DataTransferJobGetResults] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(job_create_parameters, (IOBase, bytes)): + _content = job_create_parameters + else: + _json = self._serialize.body(job_create_parameters, "CreateJobRequest") + + _request = build_create_request( + resource_group_name=resource_group_name, + account_name=account_name, + job_name=job_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DataTransferJobGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get( + self, resource_group_name: str, account_name: str, job_name: str, **kwargs: Any + ) -> _models.DataTransferJobGetResults: + """Get a Data Transfer Job. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param job_name: Name of the Data Transfer Job. Required. + :type job_name: str + :return: DataTransferJobGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DataTransferJobGetResults] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + account_name=account_name, + job_name=job_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DataTransferJobGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def pause( + self, resource_group_name: str, account_name: str, job_name: str, **kwargs: Any + ) -> _models.DataTransferJobGetResults: + """Pause a Data Transfer Job. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param job_name: Name of the Data Transfer Job. Required. + :type job_name: str + :return: DataTransferJobGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DataTransferJobGetResults] = kwargs.pop("cls", None) + + _request = build_pause_request( + resource_group_name=resource_group_name, + account_name=account_name, + job_name=job_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DataTransferJobGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def resume( + self, resource_group_name: str, account_name: str, job_name: str, **kwargs: Any + ) -> _models.DataTransferJobGetResults: + """Resumes a Data Transfer Job. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param job_name: Name of the Data Transfer Job. Required. + :type job_name: str + :return: DataTransferJobGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DataTransferJobGetResults] = kwargs.pop("cls", None) + + _request = build_resume_request( + resource_group_name=resource_group_name, + account_name=account_name, + job_name=job_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DataTransferJobGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def cancel( + self, resource_group_name: str, account_name: str, job_name: str, **kwargs: Any + ) -> _models.DataTransferJobGetResults: + """Cancels a Data Transfer Job. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param job_name: Name of the Data Transfer Job. Required. + :type job_name: str + :return: DataTransferJobGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DataTransferJobGetResults] = kwargs.pop("cls", None) + + _request = build_cancel_request( + resource_group_name=resource_group_name, + account_name=account_name, + job_name=job_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DataTransferJobGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def complete( + self, resource_group_name: str, account_name: str, job_name: str, **kwargs: Any + ) -> _models.DataTransferJobGetResults: + """Completes a Data Transfer Online Job. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param job_name: Name of the Data Transfer Job. Required. + :type job_name: str + :return: DataTransferJobGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.DataTransferJobGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DataTransferJobGetResults] = kwargs.pop("cls", None) + + _request = build_complete_request( + resource_group_name=resource_group_name, + account_name=account_name, + job_name=job_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DataTransferJobGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_by_database_account( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> Iterable["_models.DataTransferJobGetResults"]: + """Get a list of Data Transfer jobs. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either DataTransferJobGetResults or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.DataTransferJobGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DataTransferJobFeedResults] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_database_account_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("DataTransferJobFeedResults", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_database_account_region_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_database_account_region_operations.py index f8b5f9c09a6..df8ef5d933e 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_database_account_region_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_database_account_region_operations.py @@ -1,187 +1,187 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_metrics_request( - resource_group_name: str, account_name: str, region: str, subscription_id: str, *, filter: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/region/{region}/metrics", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "region": _SERIALIZER.url("region", region, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class DatabaseAccountRegionOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`database_account_region` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_metrics( - self, resource_group_name: str, account_name: str, region: str, filter: str, **kwargs: Any - ) -> Iterable["_models.Metric"]: - """Retrieves the metrics determined by the given filter for the given database account and region. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param region: Cosmos DB region, with spaces between words and each word capitalized. Required. - :type region: str - :param filter: An OData filter expression that describes a subset of metrics to return. The - parameters that can be filtered are name.value (name of the metric, can have an or of multiple - names), startTime, endTime, and timeGrain. The supported operator is eq. Required. - :type filter: str - :return: An iterator like instance of either Metric or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.Metric] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MetricListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_metrics_request( - resource_group_name=resource_group_name, - account_name=account_name, - region=region, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("MetricListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_metrics_request( + resource_group_name: str, account_name: str, region: str, subscription_id: str, *, filter: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/region/{region}/metrics", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "region": _SERIALIZER.url("region", region, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class DatabaseAccountRegionOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`database_account_region` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_metrics( + self, resource_group_name: str, account_name: str, region: str, filter: str, **kwargs: Any + ) -> Iterable["_models.Metric"]: + """Retrieves the metrics determined by the given filter for the given database account and region. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param region: Cosmos DB region, with spaces between words and each word capitalized. Required. + :type region: str + :param filter: An OData filter expression that describes a subset of metrics to return. The + parameters that can be filtered are name.value (name of the metric, can have an or of multiple + names), startTime, endTime, and timeGrain. The supported operator is eq. Required. + :type filter: str + :return: An iterator like instance of either Metric or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.Metric] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MetricListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_metrics_request( + resource_group_name=resource_group_name, + account_name=account_name, + region=region, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("MetricListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_database_accounts_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_database_accounts_operations.py index a08f1cde7f9..ebf1c50bbe0 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_database_accounts_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_database_accounts_operations.py @@ -1,2703 +1,2703 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.arm_polling import ARMPolling - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_request(resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_update_request( - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_or_update_request( - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) - - -def build_failover_priority_change_request( - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/failoverPriorityChange", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/databaseAccounts") - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_by_resource_group_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_keys_request( - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/listKeys", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_connection_strings_request( - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/listConnectionStrings", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_offline_region_request( - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/offlineRegion", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_online_region_request( - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/onlineRegion", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_read_only_keys_request( - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/readonlykeys", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_read_only_keys_request( - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/readonlykeys", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_regenerate_key_request( - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/regenerateKey", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_check_name_exists_request(account_name: str, **kwargs: Any) -> HttpRequest: - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.DocumentDB/databaseAccountNames/{accountName}") - path_format_arguments = { - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - return HttpRequest(method="HEAD", url=_url, params=_params, **kwargs) - - -def build_list_metrics_request( - resource_group_name: str, account_name: str, subscription_id: str, *, filter: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/metrics", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_usages_request( - resource_group_name: str, account_name: str, subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/usages", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_metric_definitions_request( - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/metricDefinitions", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class DatabaseAccountsOperations: # pylint: disable=too-many-public-methods - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`database_accounts` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def get(self, resource_group_name: str, account_name: str, **kwargs: Any) -> _models.DatabaseAccountGetResults: - """Retrieves the properties of an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: DatabaseAccountGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DatabaseAccountGetResults] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DatabaseAccountGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _update_initial( - self, - resource_group_name: str, - account_name: str, - update_parameters: Union[_models.DatabaseAccountUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(update_parameters, (IOBase, bytes)): - _content = update_parameters - else: - _json = self._serialize.body(update_parameters, "DatabaseAccountUpdateParameters") - - _request = build_update_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_update( - self, - resource_group_name: str, - account_name: str, - update_parameters: _models.DatabaseAccountUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.DatabaseAccountGetResults]: - """Updates the properties of an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param update_parameters: The parameters to provide for the current database account. Required. - :type update_parameters: ~azure.mgmt.cosmosdb.models.DatabaseAccountUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either DatabaseAccountGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_update( - self, - resource_group_name: str, - account_name: str, - update_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.DatabaseAccountGetResults]: - """Updates the properties of an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param update_parameters: The parameters to provide for the current database account. Required. - :type update_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either DatabaseAccountGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_update( - self, - resource_group_name: str, - account_name: str, - update_parameters: Union[_models.DatabaseAccountUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.DatabaseAccountGetResults]: - """Updates the properties of an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param update_parameters: The parameters to provide for the current database account. Is either - a DatabaseAccountUpdateParameters type or a IO[bytes] type. Required. - :type update_parameters: ~azure.mgmt.cosmosdb.models.DatabaseAccountUpdateParameters or - IO[bytes] - :return: An instance of LROPoller that returns either DatabaseAccountGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.DatabaseAccountGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._update_initial( - resource_group_name=resource_group_name, - account_name=account_name, - update_parameters=update_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("DatabaseAccountGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.DatabaseAccountGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.DatabaseAccountGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _create_or_update_initial( - self, - resource_group_name: str, - account_name: str, - create_update_parameters: Union[_models.DatabaseAccountCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_parameters, (IOBase, bytes)): - _content = create_update_parameters - else: - _json = self._serialize.body(create_update_parameters, "DatabaseAccountCreateUpdateParameters") - - _request = build_create_or_update_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_or_update( - self, - resource_group_name: str, - account_name: str, - create_update_parameters: _models.DatabaseAccountCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.DatabaseAccountGetResults]: - """Creates or updates an Azure Cosmos DB database account. The "Update" method is preferred when - performing updates on an account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param create_update_parameters: The parameters to provide for the current database account. - Required. - :type create_update_parameters: - ~azure.mgmt.cosmosdb.models.DatabaseAccountCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either DatabaseAccountGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_or_update( - self, - resource_group_name: str, - account_name: str, - create_update_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.DatabaseAccountGetResults]: - """Creates or updates an Azure Cosmos DB database account. The "Update" method is preferred when - performing updates on an account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param create_update_parameters: The parameters to provide for the current database account. - Required. - :type create_update_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either DatabaseAccountGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_or_update( - self, - resource_group_name: str, - account_name: str, - create_update_parameters: Union[_models.DatabaseAccountCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.DatabaseAccountGetResults]: - """Creates or updates an Azure Cosmos DB database account. The "Update" method is preferred when - performing updates on an account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param create_update_parameters: The parameters to provide for the current database account. Is - either a DatabaseAccountCreateUpdateParameters type or a IO[bytes] type. Required. - :type create_update_parameters: - ~azure.mgmt.cosmosdb.models.DatabaseAccountCreateUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either DatabaseAccountGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.DatabaseAccountGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_or_update_initial( - resource_group_name=resource_group_name, - account_name=account_name, - create_update_parameters=create_update_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("DatabaseAccountGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.DatabaseAccountGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.DatabaseAccountGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _delete_initial(self, resource_group_name: str, account_name: str, **kwargs: Any) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete(self, resource_group_name: str, account_name: str, **kwargs: Any) -> LROPoller[None]: - """Deletes an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_initial( - resource_group_name=resource_group_name, - account_name=account_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - def _failover_priority_change_initial( - self, - resource_group_name: str, - account_name: str, - failover_parameters: Union[_models.FailoverPolicies, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(failover_parameters, (IOBase, bytes)): - _content = failover_parameters - else: - _json = self._serialize.body(failover_parameters, "FailoverPolicies") - - _request = build_failover_priority_change_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_failover_priority_change( - self, - resource_group_name: str, - account_name: str, - failover_parameters: _models.FailoverPolicies, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[None]: - """Changes the failover priority for the Azure Cosmos DB database account. A failover priority of - 0 indicates a write region. The maximum value for a failover priority = (total number of - regions - 1). Failover priority values must be unique for each of the regions in which the - database account exists. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param failover_parameters: The new failover policies for the database account. Required. - :type failover_parameters: ~azure.mgmt.cosmosdb.models.FailoverPolicies - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_failover_priority_change( - self, - resource_group_name: str, - account_name: str, - failover_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[None]: - """Changes the failover priority for the Azure Cosmos DB database account. A failover priority of - 0 indicates a write region. The maximum value for a failover priority = (total number of - regions - 1). Failover priority values must be unique for each of the regions in which the - database account exists. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param failover_parameters: The new failover policies for the database account. Required. - :type failover_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_failover_priority_change( - self, - resource_group_name: str, - account_name: str, - failover_parameters: Union[_models.FailoverPolicies, IO[bytes]], - **kwargs: Any - ) -> LROPoller[None]: - """Changes the failover priority for the Azure Cosmos DB database account. A failover priority of - 0 indicates a write region. The maximum value for a failover priority = (total number of - regions - 1). Failover priority values must be unique for each of the regions in which the - database account exists. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param failover_parameters: The new failover policies for the database account. Is either a - FailoverPolicies type or a IO[bytes] type. Required. - :type failover_parameters: ~azure.mgmt.cosmosdb.models.FailoverPolicies or IO[bytes] - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._failover_priority_change_initial( - resource_group_name=resource_group_name, - account_name=account_name, - failover_parameters=failover_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace - def list(self, **kwargs: Any) -> Iterable["_models.DatabaseAccountGetResults"]: - """Lists all the Azure Cosmos DB database accounts available under the subscription. - - :return: An iterator like instance of either DatabaseAccountGetResults or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DatabaseAccountsListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("DatabaseAccountsListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list_by_resource_group( - self, resource_group_name: str, **kwargs: Any - ) -> Iterable["_models.DatabaseAccountGetResults"]: - """Lists all the Azure Cosmos DB database accounts available under the given resource group. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :return: An iterator like instance of either DatabaseAccountGetResults or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DatabaseAccountsListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_by_resource_group_request( - resource_group_name=resource_group_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("DatabaseAccountsListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list_keys( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> _models.DatabaseAccountListKeysResult: - """Lists the access keys for the specified Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: DatabaseAccountListKeysResult or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.DatabaseAccountListKeysResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DatabaseAccountListKeysResult] = kwargs.pop("cls", None) - - _request = build_list_keys_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DatabaseAccountListKeysResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_connection_strings( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> _models.DatabaseAccountListConnectionStringsResult: - """Lists the connection strings for the specified Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: DatabaseAccountListConnectionStringsResult or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.DatabaseAccountListConnectionStringsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DatabaseAccountListConnectionStringsResult] = kwargs.pop("cls", None) - - _request = build_list_connection_strings_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DatabaseAccountListConnectionStringsResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _offline_region_initial( - self, - resource_group_name: str, - account_name: str, - region_parameter_for_offline: Union[_models.RegionForOnlineOffline, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(region_parameter_for_offline, (IOBase, bytes)): - _content = region_parameter_for_offline - else: - _json = self._serialize.body(region_parameter_for_offline, "RegionForOnlineOffline") - - _request = build_offline_region_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_offline_region( - self, - resource_group_name: str, - account_name: str, - region_parameter_for_offline: _models.RegionForOnlineOffline, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[None]: - """Offline the specified region for the specified Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param region_parameter_for_offline: Cosmos DB region to offline for the database account. - Required. - :type region_parameter_for_offline: ~azure.mgmt.cosmosdb.models.RegionForOnlineOffline - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_offline_region( - self, - resource_group_name: str, - account_name: str, - region_parameter_for_offline: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[None]: - """Offline the specified region for the specified Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param region_parameter_for_offline: Cosmos DB region to offline for the database account. - Required. - :type region_parameter_for_offline: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_offline_region( - self, - resource_group_name: str, - account_name: str, - region_parameter_for_offline: Union[_models.RegionForOnlineOffline, IO[bytes]], - **kwargs: Any - ) -> LROPoller[None]: - """Offline the specified region for the specified Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param region_parameter_for_offline: Cosmos DB region to offline for the database account. Is - either a RegionForOnlineOffline type or a IO[bytes] type. Required. - :type region_parameter_for_offline: ~azure.mgmt.cosmosdb.models.RegionForOnlineOffline or - IO[bytes] - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._offline_region_initial( - resource_group_name=resource_group_name, - account_name=account_name, - region_parameter_for_offline=region_parameter_for_offline, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - def _online_region_initial( - self, - resource_group_name: str, - account_name: str, - region_parameter_for_online: Union[_models.RegionForOnlineOffline, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(region_parameter_for_online, (IOBase, bytes)): - _content = region_parameter_for_online - else: - _json = self._serialize.body(region_parameter_for_online, "RegionForOnlineOffline") - - _request = build_online_region_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_online_region( - self, - resource_group_name: str, - account_name: str, - region_parameter_for_online: _models.RegionForOnlineOffline, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[None]: - """Online the specified region for the specified Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param region_parameter_for_online: Cosmos DB region to online for the database account. - Required. - :type region_parameter_for_online: ~azure.mgmt.cosmosdb.models.RegionForOnlineOffline - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_online_region( - self, - resource_group_name: str, - account_name: str, - region_parameter_for_online: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[None]: - """Online the specified region for the specified Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param region_parameter_for_online: Cosmos DB region to online for the database account. - Required. - :type region_parameter_for_online: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_online_region( - self, - resource_group_name: str, - account_name: str, - region_parameter_for_online: Union[_models.RegionForOnlineOffline, IO[bytes]], - **kwargs: Any - ) -> LROPoller[None]: - """Online the specified region for the specified Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param region_parameter_for_online: Cosmos DB region to online for the database account. Is - either a RegionForOnlineOffline type or a IO[bytes] type. Required. - :type region_parameter_for_online: ~azure.mgmt.cosmosdb.models.RegionForOnlineOffline or - IO[bytes] - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._online_region_initial( - resource_group_name=resource_group_name, - account_name=account_name, - region_parameter_for_online=region_parameter_for_online, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace - def get_read_only_keys( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> _models.DatabaseAccountListReadOnlyKeysResult: - """Lists the read-only access keys for the specified Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: DatabaseAccountListReadOnlyKeysResult or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.DatabaseAccountListReadOnlyKeysResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DatabaseAccountListReadOnlyKeysResult] = kwargs.pop("cls", None) - - _request = build_get_read_only_keys_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DatabaseAccountListReadOnlyKeysResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_read_only_keys( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> _models.DatabaseAccountListReadOnlyKeysResult: - """Lists the read-only access keys for the specified Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: DatabaseAccountListReadOnlyKeysResult or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.DatabaseAccountListReadOnlyKeysResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DatabaseAccountListReadOnlyKeysResult] = kwargs.pop("cls", None) - - _request = build_list_read_only_keys_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("DatabaseAccountListReadOnlyKeysResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _regenerate_key_initial( - self, - resource_group_name: str, - account_name: str, - key_to_regenerate: Union[_models.DatabaseAccountRegenerateKeyParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(key_to_regenerate, (IOBase, bytes)): - _content = key_to_regenerate - else: - _json = self._serialize.body(key_to_regenerate, "DatabaseAccountRegenerateKeyParameters") - - _request = build_regenerate_key_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_regenerate_key( - self, - resource_group_name: str, - account_name: str, - key_to_regenerate: _models.DatabaseAccountRegenerateKeyParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[None]: - """Regenerates an access key for the specified Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param key_to_regenerate: The name of the key to regenerate. Required. - :type key_to_regenerate: ~azure.mgmt.cosmosdb.models.DatabaseAccountRegenerateKeyParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_regenerate_key( - self, - resource_group_name: str, - account_name: str, - key_to_regenerate: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[None]: - """Regenerates an access key for the specified Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param key_to_regenerate: The name of the key to regenerate. Required. - :type key_to_regenerate: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_regenerate_key( - self, - resource_group_name: str, - account_name: str, - key_to_regenerate: Union[_models.DatabaseAccountRegenerateKeyParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[None]: - """Regenerates an access key for the specified Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param key_to_regenerate: The name of the key to regenerate. Is either a - DatabaseAccountRegenerateKeyParameters type or a IO[bytes] type. Required. - :type key_to_regenerate: ~azure.mgmt.cosmosdb.models.DatabaseAccountRegenerateKeyParameters or - IO[bytes] - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._regenerate_key_initial( - resource_group_name=resource_group_name, - account_name=account_name, - key_to_regenerate=key_to_regenerate, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace - def check_name_exists(self, account_name: str, **kwargs: Any) -> bool: - """Checks that the Azure Cosmos DB account name already exists. A valid account name may contain - only lowercase letters, numbers, and the '-' character, and must be between 3 and 50 - characters. - - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: bool or the result of cls(response) - :rtype: bool - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_check_name_exists_request( - account_name=account_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 404]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - return 200 <= response.status_code <= 299 - - @distributed_trace - def list_metrics( - self, resource_group_name: str, account_name: str, filter: str, **kwargs: Any - ) -> Iterable["_models.Metric"]: - """Retrieves the metrics determined by the given filter for the given database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param filter: An OData filter expression that describes a subset of metrics to return. The - parameters that can be filtered are name.value (name of the metric, can have an or of multiple - names), startTime, endTime, and timeGrain. The supported operator is eq. Required. - :type filter: str - :return: An iterator like instance of either Metric or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.Metric] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MetricListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_metrics_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("MetricListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list_usages( - self, resource_group_name: str, account_name: str, filter: Optional[str] = None, **kwargs: Any - ) -> Iterable["_models.Usage"]: - """Retrieves the usages (most recent data) for the given database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param filter: An OData filter expression that describes a subset of usages to return. The - supported parameter is name.value (name of the metric, can have an or of multiple names). - Default value is None. - :type filter: str - :return: An iterator like instance of either Usage or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.Usage] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.UsagesResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_usages_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("UsagesResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list_metric_definitions( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> Iterable["_models.MetricDefinition"]: - """Retrieves metric definitions for the given database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either MetricDefinition or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.MetricDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MetricDefinitionsListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_metric_definitions_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("MetricDefinitionsListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request(resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_request( + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request( + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_failover_priority_change_request( + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/failoverPriorityChange", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/databaseAccounts") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_resource_group_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_keys_request( + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/listKeys", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_connection_strings_request( + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/listConnectionStrings", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_offline_region_request( + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/offlineRegion", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_online_region_request( + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/onlineRegion", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_read_only_keys_request( + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/readonlykeys", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_read_only_keys_request( + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/readonlykeys", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_regenerate_key_request( + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/regenerateKey", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_check_name_exists_request(account_name: str, **kwargs: Any) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.DocumentDB/databaseAccountNames/{accountName}") + path_format_arguments = { + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="HEAD", url=_url, params=_params, **kwargs) + + +def build_list_metrics_request( + resource_group_name: str, account_name: str, subscription_id: str, *, filter: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/metrics", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_usages_request( + resource_group_name: str, account_name: str, subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/usages", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_metric_definitions_request( + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/metricDefinitions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class DatabaseAccountsOperations: # pylint: disable=too-many-public-methods + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`database_accounts` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, resource_group_name: str, account_name: str, **kwargs: Any) -> _models.DatabaseAccountGetResults: + """Retrieves the properties of an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: DatabaseAccountGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DatabaseAccountGetResults] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DatabaseAccountGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _update_initial( + self, + resource_group_name: str, + account_name: str, + update_parameters: Union[_models.DatabaseAccountUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(update_parameters, (IOBase, bytes)): + _content = update_parameters + else: + _json = self._serialize.body(update_parameters, "DatabaseAccountUpdateParameters") + + _request = build_update_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_update( + self, + resource_group_name: str, + account_name: str, + update_parameters: _models.DatabaseAccountUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DatabaseAccountGetResults]: + """Updates the properties of an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param update_parameters: The parameters to provide for the current database account. Required. + :type update_parameters: ~azure.mgmt.cosmosdb.models.DatabaseAccountUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either DatabaseAccountGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update( + self, + resource_group_name: str, + account_name: str, + update_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DatabaseAccountGetResults]: + """Updates the properties of an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param update_parameters: The parameters to provide for the current database account. Required. + :type update_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either DatabaseAccountGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update( + self, + resource_group_name: str, + account_name: str, + update_parameters: Union[_models.DatabaseAccountUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.DatabaseAccountGetResults]: + """Updates the properties of an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param update_parameters: The parameters to provide for the current database account. Is either + a DatabaseAccountUpdateParameters type or a IO[bytes] type. Required. + :type update_parameters: ~azure.mgmt.cosmosdb.models.DatabaseAccountUpdateParameters or + IO[bytes] + :return: An instance of LROPoller that returns either DatabaseAccountGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DatabaseAccountGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._update_initial( + resource_group_name=resource_group_name, + account_name=account_name, + update_parameters=update_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("DatabaseAccountGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.DatabaseAccountGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.DatabaseAccountGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _create_or_update_initial( + self, + resource_group_name: str, + account_name: str, + create_update_parameters: Union[_models.DatabaseAccountCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_parameters, (IOBase, bytes)): + _content = create_update_parameters + else: + _json = self._serialize.body(create_update_parameters, "DatabaseAccountCreateUpdateParameters") + + _request = build_create_or_update_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + account_name: str, + create_update_parameters: _models.DatabaseAccountCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DatabaseAccountGetResults]: + """Creates or updates an Azure Cosmos DB database account. The "Update" method is preferred when + performing updates on an account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param create_update_parameters: The parameters to provide for the current database account. + Required. + :type create_update_parameters: + ~azure.mgmt.cosmosdb.models.DatabaseAccountCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either DatabaseAccountGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + account_name: str, + create_update_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DatabaseAccountGetResults]: + """Creates or updates an Azure Cosmos DB database account. The "Update" method is preferred when + performing updates on an account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param create_update_parameters: The parameters to provide for the current database account. + Required. + :type create_update_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either DatabaseAccountGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + account_name: str, + create_update_parameters: Union[_models.DatabaseAccountCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.DatabaseAccountGetResults]: + """Creates or updates an Azure Cosmos DB database account. The "Update" method is preferred when + performing updates on an account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param create_update_parameters: The parameters to provide for the current database account. Is + either a DatabaseAccountCreateUpdateParameters type or a IO[bytes] type. Required. + :type create_update_parameters: + ~azure.mgmt.cosmosdb.models.DatabaseAccountCreateUpdateParameters or IO[bytes] + :return: An instance of LROPoller that returns either DatabaseAccountGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DatabaseAccountGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + account_name=account_name, + create_update_parameters=create_update_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("DatabaseAccountGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.DatabaseAccountGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.DatabaseAccountGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_initial(self, resource_group_name: str, account_name: str, **kwargs: Any) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete(self, resource_group_name: str, account_name: str, **kwargs: Any) -> LROPoller[None]: + """Deletes an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + account_name=account_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + def _failover_priority_change_initial( + self, + resource_group_name: str, + account_name: str, + failover_parameters: Union[_models.FailoverPolicies, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(failover_parameters, (IOBase, bytes)): + _content = failover_parameters + else: + _json = self._serialize.body(failover_parameters, "FailoverPolicies") + + _request = build_failover_priority_change_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_failover_priority_change( + self, + resource_group_name: str, + account_name: str, + failover_parameters: _models.FailoverPolicies, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: + """Changes the failover priority for the Azure Cosmos DB database account. A failover priority of + 0 indicates a write region. The maximum value for a failover priority = (total number of + regions - 1). Failover priority values must be unique for each of the regions in which the + database account exists. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param failover_parameters: The new failover policies for the database account. Required. + :type failover_parameters: ~azure.mgmt.cosmosdb.models.FailoverPolicies + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_failover_priority_change( + self, + resource_group_name: str, + account_name: str, + failover_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: + """Changes the failover priority for the Azure Cosmos DB database account. A failover priority of + 0 indicates a write region. The maximum value for a failover priority = (total number of + regions - 1). Failover priority values must be unique for each of the regions in which the + database account exists. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param failover_parameters: The new failover policies for the database account. Required. + :type failover_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_failover_priority_change( + self, + resource_group_name: str, + account_name: str, + failover_parameters: Union[_models.FailoverPolicies, IO[bytes]], + **kwargs: Any + ) -> LROPoller[None]: + """Changes the failover priority for the Azure Cosmos DB database account. A failover priority of + 0 indicates a write region. The maximum value for a failover priority = (total number of + regions - 1). Failover priority values must be unique for each of the regions in which the + database account exists. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param failover_parameters: The new failover policies for the database account. Is either a + FailoverPolicies type or a IO[bytes] type. Required. + :type failover_parameters: ~azure.mgmt.cosmosdb.models.FailoverPolicies or IO[bytes] + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._failover_priority_change_initial( + resource_group_name=resource_group_name, + account_name=account_name, + failover_parameters=failover_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.DatabaseAccountGetResults"]: + """Lists all the Azure Cosmos DB database accounts available under the subscription. + + :return: An iterator like instance of either DatabaseAccountGetResults or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DatabaseAccountsListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("DatabaseAccountsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_resource_group( + self, resource_group_name: str, **kwargs: Any + ) -> Iterable["_models.DatabaseAccountGetResults"]: + """Lists all the Azure Cosmos DB database accounts available under the given resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :return: An iterator like instance of either DatabaseAccountGetResults or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.DatabaseAccountGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DatabaseAccountsListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("DatabaseAccountsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_keys( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> _models.DatabaseAccountListKeysResult: + """Lists the access keys for the specified Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: DatabaseAccountListKeysResult or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.DatabaseAccountListKeysResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DatabaseAccountListKeysResult] = kwargs.pop("cls", None) + + _request = build_list_keys_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DatabaseAccountListKeysResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_connection_strings( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> _models.DatabaseAccountListConnectionStringsResult: + """Lists the connection strings for the specified Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: DatabaseAccountListConnectionStringsResult or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.DatabaseAccountListConnectionStringsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DatabaseAccountListConnectionStringsResult] = kwargs.pop("cls", None) + + _request = build_list_connection_strings_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DatabaseAccountListConnectionStringsResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _offline_region_initial( + self, + resource_group_name: str, + account_name: str, + region_parameter_for_offline: Union[_models.RegionForOnlineOffline, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(region_parameter_for_offline, (IOBase, bytes)): + _content = region_parameter_for_offline + else: + _json = self._serialize.body(region_parameter_for_offline, "RegionForOnlineOffline") + + _request = build_offline_region_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_offline_region( + self, + resource_group_name: str, + account_name: str, + region_parameter_for_offline: _models.RegionForOnlineOffline, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: + """Offline the specified region for the specified Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param region_parameter_for_offline: Cosmos DB region to offline for the database account. + Required. + :type region_parameter_for_offline: ~azure.mgmt.cosmosdb.models.RegionForOnlineOffline + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_offline_region( + self, + resource_group_name: str, + account_name: str, + region_parameter_for_offline: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: + """Offline the specified region for the specified Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param region_parameter_for_offline: Cosmos DB region to offline for the database account. + Required. + :type region_parameter_for_offline: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_offline_region( + self, + resource_group_name: str, + account_name: str, + region_parameter_for_offline: Union[_models.RegionForOnlineOffline, IO[bytes]], + **kwargs: Any + ) -> LROPoller[None]: + """Offline the specified region for the specified Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param region_parameter_for_offline: Cosmos DB region to offline for the database account. Is + either a RegionForOnlineOffline type or a IO[bytes] type. Required. + :type region_parameter_for_offline: ~azure.mgmt.cosmosdb.models.RegionForOnlineOffline or + IO[bytes] + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._offline_region_initial( + resource_group_name=resource_group_name, + account_name=account_name, + region_parameter_for_offline=region_parameter_for_offline, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + def _online_region_initial( + self, + resource_group_name: str, + account_name: str, + region_parameter_for_online: Union[_models.RegionForOnlineOffline, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(region_parameter_for_online, (IOBase, bytes)): + _content = region_parameter_for_online + else: + _json = self._serialize.body(region_parameter_for_online, "RegionForOnlineOffline") + + _request = build_online_region_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_online_region( + self, + resource_group_name: str, + account_name: str, + region_parameter_for_online: _models.RegionForOnlineOffline, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: + """Online the specified region for the specified Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param region_parameter_for_online: Cosmos DB region to online for the database account. + Required. + :type region_parameter_for_online: ~azure.mgmt.cosmosdb.models.RegionForOnlineOffline + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_online_region( + self, + resource_group_name: str, + account_name: str, + region_parameter_for_online: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: + """Online the specified region for the specified Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param region_parameter_for_online: Cosmos DB region to online for the database account. + Required. + :type region_parameter_for_online: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_online_region( + self, + resource_group_name: str, + account_name: str, + region_parameter_for_online: Union[_models.RegionForOnlineOffline, IO[bytes]], + **kwargs: Any + ) -> LROPoller[None]: + """Online the specified region for the specified Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param region_parameter_for_online: Cosmos DB region to online for the database account. Is + either a RegionForOnlineOffline type or a IO[bytes] type. Required. + :type region_parameter_for_online: ~azure.mgmt.cosmosdb.models.RegionForOnlineOffline or + IO[bytes] + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._online_region_initial( + resource_group_name=resource_group_name, + account_name=account_name, + region_parameter_for_online=region_parameter_for_online, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def get_read_only_keys( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> _models.DatabaseAccountListReadOnlyKeysResult: + """Lists the read-only access keys for the specified Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: DatabaseAccountListReadOnlyKeysResult or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.DatabaseAccountListReadOnlyKeysResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DatabaseAccountListReadOnlyKeysResult] = kwargs.pop("cls", None) + + _request = build_get_read_only_keys_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DatabaseAccountListReadOnlyKeysResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_read_only_keys( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> _models.DatabaseAccountListReadOnlyKeysResult: + """Lists the read-only access keys for the specified Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: DatabaseAccountListReadOnlyKeysResult or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.DatabaseAccountListReadOnlyKeysResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DatabaseAccountListReadOnlyKeysResult] = kwargs.pop("cls", None) + + _request = build_list_read_only_keys_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DatabaseAccountListReadOnlyKeysResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _regenerate_key_initial( + self, + resource_group_name: str, + account_name: str, + key_to_regenerate: Union[_models.DatabaseAccountRegenerateKeyParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(key_to_regenerate, (IOBase, bytes)): + _content = key_to_regenerate + else: + _json = self._serialize.body(key_to_regenerate, "DatabaseAccountRegenerateKeyParameters") + + _request = build_regenerate_key_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_regenerate_key( + self, + resource_group_name: str, + account_name: str, + key_to_regenerate: _models.DatabaseAccountRegenerateKeyParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: + """Regenerates an access key for the specified Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param key_to_regenerate: The name of the key to regenerate. Required. + :type key_to_regenerate: ~azure.mgmt.cosmosdb.models.DatabaseAccountRegenerateKeyParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_regenerate_key( + self, + resource_group_name: str, + account_name: str, + key_to_regenerate: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: + """Regenerates an access key for the specified Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param key_to_regenerate: The name of the key to regenerate. Required. + :type key_to_regenerate: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_regenerate_key( + self, + resource_group_name: str, + account_name: str, + key_to_regenerate: Union[_models.DatabaseAccountRegenerateKeyParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[None]: + """Regenerates an access key for the specified Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param key_to_regenerate: The name of the key to regenerate. Is either a + DatabaseAccountRegenerateKeyParameters type or a IO[bytes] type. Required. + :type key_to_regenerate: ~azure.mgmt.cosmosdb.models.DatabaseAccountRegenerateKeyParameters or + IO[bytes] + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._regenerate_key_initial( + resource_group_name=resource_group_name, + account_name=account_name, + key_to_regenerate=key_to_regenerate, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def check_name_exists(self, account_name: str, **kwargs: Any) -> bool: + """Checks that the Azure Cosmos DB account name already exists. A valid account name may contain + only lowercase letters, numbers, and the '-' character, and must be between 3 and 50 + characters. + + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: bool or the result of cls(response) + :rtype: bool + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_check_name_exists_request( + account_name=account_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + return 200 <= response.status_code <= 299 + + @distributed_trace + def list_metrics( + self, resource_group_name: str, account_name: str, filter: str, **kwargs: Any + ) -> Iterable["_models.Metric"]: + """Retrieves the metrics determined by the given filter for the given database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param filter: An OData filter expression that describes a subset of metrics to return. The + parameters that can be filtered are name.value (name of the metric, can have an or of multiple + names), startTime, endTime, and timeGrain. The supported operator is eq. Required. + :type filter: str + :return: An iterator like instance of either Metric or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.Metric] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MetricListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_metrics_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("MetricListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_usages( + self, resource_group_name: str, account_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.Usage"]: + """Retrieves the usages (most recent data) for the given database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param filter: An OData filter expression that describes a subset of usages to return. The + supported parameter is name.value (name of the metric, can have an or of multiple names). + Default value is None. + :type filter: str + :return: An iterator like instance of either Usage or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.Usage] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.UsagesResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_usages_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("UsagesResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_metric_definitions( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> Iterable["_models.MetricDefinition"]: + """Retrieves metric definitions for the given database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either MetricDefinition or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.MetricDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MetricDefinitionsListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_metric_definitions_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("MetricDefinitionsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_database_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_database_operations.py index d6dfa08aeb9..5739b36aa4a 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_database_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_database_operations.py @@ -1,450 +1,450 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_metrics_request( - resource_group_name: str, account_name: str, database_rid: str, subscription_id: str, *, filter: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/databases/{databaseRid}/metrics", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseRid": _SERIALIZER.url("database_rid", database_rid, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_usages_request( - resource_group_name: str, - account_name: str, - database_rid: str, - subscription_id: str, - *, - filter: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/databases/{databaseRid}/usages", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseRid": _SERIALIZER.url("database_rid", database_rid, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_metric_definitions_request( - resource_group_name: str, account_name: str, database_rid: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/databases/{databaseRid}/metricDefinitions", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseRid": _SERIALIZER.url("database_rid", database_rid, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class DatabaseOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`database` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_metrics( - self, resource_group_name: str, account_name: str, database_rid: str, filter: str, **kwargs: Any - ) -> Iterable["_models.Metric"]: - """Retrieves the metrics determined by the given filter for the given database account and - database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_rid: Cosmos DB database rid. Required. - :type database_rid: str - :param filter: An OData filter expression that describes a subset of metrics to return. The - parameters that can be filtered are name.value (name of the metric, can have an or of multiple - names), startTime, endTime, and timeGrain. The supported operator is eq. Required. - :type filter: str - :return: An iterator like instance of either Metric or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.Metric] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MetricListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_metrics_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_rid=database_rid, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("MetricListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list_usages( - self, - resource_group_name: str, - account_name: str, - database_rid: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> Iterable["_models.Usage"]: - """Retrieves the usages (most recent data) for the given database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_rid: Cosmos DB database rid. Required. - :type database_rid: str - :param filter: An OData filter expression that describes a subset of usages to return. The - supported parameter is name.value (name of the metric, can have an or of multiple names). - Default value is None. - :type filter: str - :return: An iterator like instance of either Usage or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.Usage] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.UsagesResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_usages_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_rid=database_rid, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("UsagesResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list_metric_definitions( - self, resource_group_name: str, account_name: str, database_rid: str, **kwargs: Any - ) -> Iterable["_models.MetricDefinition"]: - """Retrieves metric definitions for the given database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_rid: Cosmos DB database rid. Required. - :type database_rid: str - :return: An iterator like instance of either MetricDefinition or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.MetricDefinition] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MetricDefinitionsListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_metric_definitions_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_rid=database_rid, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("MetricDefinitionsListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_metrics_request( + resource_group_name: str, account_name: str, database_rid: str, subscription_id: str, *, filter: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/databases/{databaseRid}/metrics", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseRid": _SERIALIZER.url("database_rid", database_rid, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_usages_request( + resource_group_name: str, + account_name: str, + database_rid: str, + subscription_id: str, + *, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/databases/{databaseRid}/usages", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseRid": _SERIALIZER.url("database_rid", database_rid, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_metric_definitions_request( + resource_group_name: str, account_name: str, database_rid: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/databases/{databaseRid}/metricDefinitions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseRid": _SERIALIZER.url("database_rid", database_rid, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class DatabaseOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`database` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_metrics( + self, resource_group_name: str, account_name: str, database_rid: str, filter: str, **kwargs: Any + ) -> Iterable["_models.Metric"]: + """Retrieves the metrics determined by the given filter for the given database account and + database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_rid: Cosmos DB database rid. Required. + :type database_rid: str + :param filter: An OData filter expression that describes a subset of metrics to return. The + parameters that can be filtered are name.value (name of the metric, can have an or of multiple + names), startTime, endTime, and timeGrain. The supported operator is eq. Required. + :type filter: str + :return: An iterator like instance of either Metric or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.Metric] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MetricListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_metrics_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_rid=database_rid, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("MetricListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_usages( + self, + resource_group_name: str, + account_name: str, + database_rid: str, + filter: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.Usage"]: + """Retrieves the usages (most recent data) for the given database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_rid: Cosmos DB database rid. Required. + :type database_rid: str + :param filter: An OData filter expression that describes a subset of usages to return. The + supported parameter is name.value (name of the metric, can have an or of multiple names). + Default value is None. + :type filter: str + :return: An iterator like instance of either Usage or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.Usage] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.UsagesResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_usages_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_rid=database_rid, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("UsagesResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_metric_definitions( + self, resource_group_name: str, account_name: str, database_rid: str, **kwargs: Any + ) -> Iterable["_models.MetricDefinition"]: + """Retrieves metric definitions for the given database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_rid: Cosmos DB database rid. Required. + :type database_rid: str + :return: An iterator like instance of either MetricDefinition or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.MetricDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MetricDefinitionsListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_metric_definitions_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_rid=database_rid, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("MetricDefinitionsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_graph_resources_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_graph_resources_operations.py index 27c347f759a..f7f7a4927f1 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_graph_resources_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_graph_resources_operations.py @@ -1,680 +1,680 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.arm_polling import ARMPolling - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_graphs_request( - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/graphs", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_graph_request( - resource_group_name: str, account_name: str, graph_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/graphs/{graphName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "graphName": _SERIALIZER.url("graph_name", graph_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_update_graph_request( - resource_group_name: str, account_name: str, graph_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/graphs/{graphName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "graphName": _SERIALIZER.url("graph_name", graph_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_graph_resource_request( - resource_group_name: str, account_name: str, graph_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/graphs/{graphName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "graphName": _SERIALIZER.url("graph_name", graph_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) - - -class GraphResourcesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`graph_resources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_graphs( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> Iterable["_models.GraphResourceGetResults"]: - """Lists the graphs under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either GraphResourceGetResults or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.GraphResourceGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.GraphResourcesListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_graphs_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("GraphResourcesListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get_graph( - self, resource_group_name: str, account_name: str, graph_name: str, **kwargs: Any - ) -> _models.GraphResourceGetResults: - """Gets the Graph resource under an existing Azure Cosmos DB database account with the provided - name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param graph_name: Cosmos DB graph resource name. Required. - :type graph_name: str - :return: GraphResourceGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.GraphResourceGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.GraphResourceGetResults] = kwargs.pop("cls", None) - - _request = build_get_graph_request( - resource_group_name=resource_group_name, - account_name=account_name, - graph_name=graph_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("GraphResourceGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _create_update_graph_initial( - self, - resource_group_name: str, - account_name: str, - graph_name: str, - create_update_graph_parameters: Union[_models.GraphResourceCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_graph_parameters, (IOBase, bytes)): - _content = create_update_graph_parameters - else: - _json = self._serialize.body(create_update_graph_parameters, "GraphResourceCreateUpdateParameters") - - _request = build_create_update_graph_request( - resource_group_name=resource_group_name, - account_name=account_name, - graph_name=graph_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_update_graph( - self, - resource_group_name: str, - account_name: str, - graph_name: str, - create_update_graph_parameters: _models.GraphResourceCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.GraphResourceGetResults]: - """Create or update an Azure Cosmos DB Graph. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param graph_name: Cosmos DB graph resource name. Required. - :type graph_name: str - :param create_update_graph_parameters: The parameters to provide for the current graph. - Required. - :type create_update_graph_parameters: - ~azure.mgmt.cosmosdb.models.GraphResourceCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either GraphResourceGetResults or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GraphResourceGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_update_graph( - self, - resource_group_name: str, - account_name: str, - graph_name: str, - create_update_graph_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.GraphResourceGetResults]: - """Create or update an Azure Cosmos DB Graph. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param graph_name: Cosmos DB graph resource name. Required. - :type graph_name: str - :param create_update_graph_parameters: The parameters to provide for the current graph. - Required. - :type create_update_graph_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either GraphResourceGetResults or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GraphResourceGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_update_graph( - self, - resource_group_name: str, - account_name: str, - graph_name: str, - create_update_graph_parameters: Union[_models.GraphResourceCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.GraphResourceGetResults]: - """Create or update an Azure Cosmos DB Graph. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param graph_name: Cosmos DB graph resource name. Required. - :type graph_name: str - :param create_update_graph_parameters: The parameters to provide for the current graph. Is - either a GraphResourceCreateUpdateParameters type or a IO[bytes] type. Required. - :type create_update_graph_parameters: - ~azure.mgmt.cosmosdb.models.GraphResourceCreateUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either GraphResourceGetResults or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GraphResourceGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.GraphResourceGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_update_graph_initial( - resource_group_name=resource_group_name, - account_name=account_name, - graph_name=graph_name, - create_update_graph_parameters=create_update_graph_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("GraphResourceGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.GraphResourceGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.GraphResourceGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _delete_graph_resource_initial( - self, resource_group_name: str, account_name: str, graph_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_graph_resource_request( - resource_group_name=resource_group_name, - account_name=account_name, - graph_name=graph_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202, 204]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete_graph_resource( - self, resource_group_name: str, account_name: str, graph_name: str, **kwargs: Any - ) -> LROPoller[None]: - """Deletes an existing Azure Cosmos DB Graph Resource. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param graph_name: Cosmos DB graph resource name. Required. - :type graph_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_graph_resource_initial( - resource_group_name=resource_group_name, - account_name=account_name, - graph_name=graph_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_graphs_request( + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/graphs", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_graph_request( + resource_group_name: str, account_name: str, graph_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/graphs/{graphName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "graphName": _SERIALIZER.url("graph_name", graph_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_update_graph_request( + resource_group_name: str, account_name: str, graph_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/graphs/{graphName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "graphName": _SERIALIZER.url("graph_name", graph_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_graph_resource_request( + resource_group_name: str, account_name: str, graph_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/graphs/{graphName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "graphName": _SERIALIZER.url("graph_name", graph_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +class GraphResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`graph_resources` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_graphs( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> Iterable["_models.GraphResourceGetResults"]: + """Lists the graphs under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either GraphResourceGetResults or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.GraphResourceGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.GraphResourcesListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_graphs_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("GraphResourcesListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get_graph( + self, resource_group_name: str, account_name: str, graph_name: str, **kwargs: Any + ) -> _models.GraphResourceGetResults: + """Gets the Graph resource under an existing Azure Cosmos DB database account with the provided + name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param graph_name: Cosmos DB graph resource name. Required. + :type graph_name: str + :return: GraphResourceGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.GraphResourceGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.GraphResourceGetResults] = kwargs.pop("cls", None) + + _request = build_get_graph_request( + resource_group_name=resource_group_name, + account_name=account_name, + graph_name=graph_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("GraphResourceGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_update_graph_initial( + self, + resource_group_name: str, + account_name: str, + graph_name: str, + create_update_graph_parameters: Union[_models.GraphResourceCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_graph_parameters, (IOBase, bytes)): + _content = create_update_graph_parameters + else: + _json = self._serialize.body(create_update_graph_parameters, "GraphResourceCreateUpdateParameters") + + _request = build_create_update_graph_request( + resource_group_name=resource_group_name, + account_name=account_name, + graph_name=graph_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_update_graph( + self, + resource_group_name: str, + account_name: str, + graph_name: str, + create_update_graph_parameters: _models.GraphResourceCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.GraphResourceGetResults]: + """Create or update an Azure Cosmos DB Graph. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param graph_name: Cosmos DB graph resource name. Required. + :type graph_name: str + :param create_update_graph_parameters: The parameters to provide for the current graph. + Required. + :type create_update_graph_parameters: + ~azure.mgmt.cosmosdb.models.GraphResourceCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either GraphResourceGetResults or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GraphResourceGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_update_graph( + self, + resource_group_name: str, + account_name: str, + graph_name: str, + create_update_graph_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.GraphResourceGetResults]: + """Create or update an Azure Cosmos DB Graph. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param graph_name: Cosmos DB graph resource name. Required. + :type graph_name: str + :param create_update_graph_parameters: The parameters to provide for the current graph. + Required. + :type create_update_graph_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either GraphResourceGetResults or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GraphResourceGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_update_graph( + self, + resource_group_name: str, + account_name: str, + graph_name: str, + create_update_graph_parameters: Union[_models.GraphResourceCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.GraphResourceGetResults]: + """Create or update an Azure Cosmos DB Graph. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param graph_name: Cosmos DB graph resource name. Required. + :type graph_name: str + :param create_update_graph_parameters: The parameters to provide for the current graph. Is + either a GraphResourceCreateUpdateParameters type or a IO[bytes] type. Required. + :type create_update_graph_parameters: + ~azure.mgmt.cosmosdb.models.GraphResourceCreateUpdateParameters or IO[bytes] + :return: An instance of LROPoller that returns either GraphResourceGetResults or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GraphResourceGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.GraphResourceGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_update_graph_initial( + resource_group_name=resource_group_name, + account_name=account_name, + graph_name=graph_name, + create_update_graph_parameters=create_update_graph_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("GraphResourceGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.GraphResourceGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.GraphResourceGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_graph_resource_initial( + self, resource_group_name: str, account_name: str, graph_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_graph_resource_request( + resource_group_name=resource_group_name, + account_name=account_name, + graph_name=graph_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete_graph_resource( + self, resource_group_name: str, account_name: str, graph_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Deletes an existing Azure Cosmos DB Graph Resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param graph_name: Cosmos DB graph resource name. Required. + :type graph_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_graph_resource_initial( + resource_group_name=resource_group_name, + account_name=account_name, + graph_name=graph_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_gremlin_resources_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_gremlin_resources_operations.py index f24eba43c40..c0c945a4a69 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_gremlin_resources_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_gremlin_resources_operations.py @@ -1,2982 +1,2982 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.arm_polling import ARMPolling - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_gremlin_databases_request( - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_gremlin_database_request( - resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_update_gremlin_database_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_gremlin_database_request( - resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) - - -def build_get_gremlin_database_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_update_gremlin_database_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_migrate_gremlin_database_to_autoscale_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToAutoscale", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_migrate_gremlin_database_to_manual_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToManualThroughput", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_gremlin_graphs_request( - resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_gremlin_graph_request( - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "graphName": _SERIALIZER.url("graph_name", graph_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_update_gremlin_graph_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "graphName": _SERIALIZER.url("graph_name", graph_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_gremlin_graph_request( - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "graphName": _SERIALIZER.url("graph_name", graph_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) - - -def build_get_gremlin_graph_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "graphName": _SERIALIZER.url("graph_name", graph_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_update_gremlin_graph_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "graphName": _SERIALIZER.url("graph_name", graph_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_migrate_gremlin_graph_to_autoscale_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToAutoscale", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "graphName": _SERIALIZER.url("graph_name", graph_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_migrate_gremlin_graph_to_manual_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToManualThroughput", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "graphName": _SERIALIZER.url("graph_name", graph_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_retrieve_continuous_backup_information_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/retrieveContinuousBackupInformation", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "graphName": _SERIALIZER.url("graph_name", graph_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -class GremlinResourcesOperations: # pylint: disable=too-many-public-methods - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`gremlin_resources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_gremlin_databases( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> Iterable["_models.GremlinDatabaseGetResults"]: - """Lists the Gremlin databases under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either GremlinDatabaseGetResults or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.GremlinDatabaseListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_gremlin_databases_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("GremlinDatabaseListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get_gremlin_database( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> _models.GremlinDatabaseGetResults: - """Gets the Gremlin databases under an existing Azure Cosmos DB database account with the provided - name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: GremlinDatabaseGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.GremlinDatabaseGetResults] = kwargs.pop("cls", None) - - _request = build_get_gremlin_database_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("GremlinDatabaseGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _create_update_gremlin_database_initial( - self, - resource_group_name: str, - account_name: str, - database_name: str, - create_update_gremlin_database_parameters: Union[_models.GremlinDatabaseCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_gremlin_database_parameters, (IOBase, bytes)): - _content = create_update_gremlin_database_parameters - else: - _json = self._serialize.body( - create_update_gremlin_database_parameters, "GremlinDatabaseCreateUpdateParameters" - ) - - _request = build_create_update_gremlin_database_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_update_gremlin_database( - self, - resource_group_name: str, - account_name: str, - database_name: str, - create_update_gremlin_database_parameters: _models.GremlinDatabaseCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.GremlinDatabaseGetResults]: - """Create or update an Azure Cosmos DB Gremlin database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param create_update_gremlin_database_parameters: The parameters to provide for the current - Gremlin database. Required. - :type create_update_gremlin_database_parameters: - ~azure.mgmt.cosmosdb.models.GremlinDatabaseCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either GremlinDatabaseGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_update_gremlin_database( - self, - resource_group_name: str, - account_name: str, - database_name: str, - create_update_gremlin_database_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.GremlinDatabaseGetResults]: - """Create or update an Azure Cosmos DB Gremlin database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param create_update_gremlin_database_parameters: The parameters to provide for the current - Gremlin database. Required. - :type create_update_gremlin_database_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either GremlinDatabaseGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_update_gremlin_database( - self, - resource_group_name: str, - account_name: str, - database_name: str, - create_update_gremlin_database_parameters: Union[_models.GremlinDatabaseCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.GremlinDatabaseGetResults]: - """Create or update an Azure Cosmos DB Gremlin database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param create_update_gremlin_database_parameters: The parameters to provide for the current - Gremlin database. Is either a GremlinDatabaseCreateUpdateParameters type or a IO[bytes] type. - Required. - :type create_update_gremlin_database_parameters: - ~azure.mgmt.cosmosdb.models.GremlinDatabaseCreateUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either GremlinDatabaseGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.GremlinDatabaseGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_update_gremlin_database_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - create_update_gremlin_database_parameters=create_update_gremlin_database_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("GremlinDatabaseGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.GremlinDatabaseGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.GremlinDatabaseGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _delete_gremlin_database_initial( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_gremlin_database_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete_gremlin_database( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> LROPoller[None]: - """Deletes an existing Azure Cosmos DB Gremlin database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_gremlin_database_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace - def get_gremlin_database_throughput( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> _models.ThroughputSettingsGetResults: - """Gets the RUs per second of the Gremlin database under an existing Azure Cosmos DB database - account with the provided name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: ThroughputSettingsGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - - _request = build_get_gremlin_database_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _update_gremlin_database_throughput_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(update_throughput_parameters, (IOBase, bytes)): - _content = update_throughput_parameters - else: - _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") - - _request = build_update_gremlin_database_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_update_gremlin_database_throughput( - self, - resource_group_name: str, - account_name: str, - database_name: str, - update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Gremlin database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current Gremlin database. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_update_gremlin_database_throughput( - self, - resource_group_name: str, - account_name: str, - database_name: str, - update_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Gremlin database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current Gremlin database. Required. - :type update_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_update_gremlin_database_throughput( - self, - resource_group_name: str, - account_name: str, - database_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Gremlin database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current Gremlin database. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] - type. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._update_gremlin_database_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - update_throughput_parameters=update_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _migrate_gremlin_database_to_autoscale_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_gremlin_database_to_autoscale_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_migrate_gremlin_database_to_autoscale( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB Gremlin database from manual throughput to autoscale. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._migrate_gremlin_database_to_autoscale_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _migrate_gremlin_database_to_manual_throughput_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_gremlin_database_to_manual_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_migrate_gremlin_database_to_manual_throughput( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB Gremlin database from autoscale to manual throughput. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._migrate_gremlin_database_to_manual_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @distributed_trace - def list_gremlin_graphs( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> Iterable["_models.GremlinGraphGetResults"]: - """Lists the Gremlin graph under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: An iterator like instance of either GremlinGraphGetResults or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.GremlinGraphGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.GremlinGraphListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_gremlin_graphs_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("GremlinGraphListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get_gremlin_graph( - self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any - ) -> _models.GremlinGraphGetResults: - """Gets the Gremlin graph under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param graph_name: Cosmos DB graph name. Required. - :type graph_name: str - :return: GremlinGraphGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.GremlinGraphGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.GremlinGraphGetResults] = kwargs.pop("cls", None) - - _request = build_get_gremlin_graph_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - graph_name=graph_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("GremlinGraphGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _create_update_gremlin_graph_initial( - self, - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - create_update_gremlin_graph_parameters: Union[_models.GremlinGraphCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_gremlin_graph_parameters, (IOBase, bytes)): - _content = create_update_gremlin_graph_parameters - else: - _json = self._serialize.body(create_update_gremlin_graph_parameters, "GremlinGraphCreateUpdateParameters") - - _request = build_create_update_gremlin_graph_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - graph_name=graph_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_update_gremlin_graph( - self, - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - create_update_gremlin_graph_parameters: _models.GremlinGraphCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.GremlinGraphGetResults]: - """Create or update an Azure Cosmos DB Gremlin graph. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param graph_name: Cosmos DB graph name. Required. - :type graph_name: str - :param create_update_gremlin_graph_parameters: The parameters to provide for the current - Gremlin graph. Required. - :type create_update_gremlin_graph_parameters: - ~azure.mgmt.cosmosdb.models.GremlinGraphCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either GremlinGraphGetResults or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinGraphGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_update_gremlin_graph( - self, - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - create_update_gremlin_graph_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.GremlinGraphGetResults]: - """Create or update an Azure Cosmos DB Gremlin graph. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param graph_name: Cosmos DB graph name. Required. - :type graph_name: str - :param create_update_gremlin_graph_parameters: The parameters to provide for the current - Gremlin graph. Required. - :type create_update_gremlin_graph_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either GremlinGraphGetResults or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinGraphGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_update_gremlin_graph( - self, - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - create_update_gremlin_graph_parameters: Union[_models.GremlinGraphCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.GremlinGraphGetResults]: - """Create or update an Azure Cosmos DB Gremlin graph. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param graph_name: Cosmos DB graph name. Required. - :type graph_name: str - :param create_update_gremlin_graph_parameters: The parameters to provide for the current - Gremlin graph. Is either a GremlinGraphCreateUpdateParameters type or a IO[bytes] type. - Required. - :type create_update_gremlin_graph_parameters: - ~azure.mgmt.cosmosdb.models.GremlinGraphCreateUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either GremlinGraphGetResults or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinGraphGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.GremlinGraphGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_update_gremlin_graph_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - graph_name=graph_name, - create_update_gremlin_graph_parameters=create_update_gremlin_graph_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("GremlinGraphGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.GremlinGraphGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.GremlinGraphGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _delete_gremlin_graph_initial( - self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_gremlin_graph_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - graph_name=graph_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete_gremlin_graph( - self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any - ) -> LROPoller[None]: - """Deletes an existing Azure Cosmos DB Gremlin graph. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param graph_name: Cosmos DB graph name. Required. - :type graph_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_gremlin_graph_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - graph_name=graph_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace - def get_gremlin_graph_throughput( - self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any - ) -> _models.ThroughputSettingsGetResults: - """Gets the Gremlin graph throughput under an existing Azure Cosmos DB database account with the - provided name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param graph_name: Cosmos DB graph name. Required. - :type graph_name: str - :return: ThroughputSettingsGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - - _request = build_get_gremlin_graph_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - graph_name=graph_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _update_gremlin_graph_throughput_initial( - self, - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(update_throughput_parameters, (IOBase, bytes)): - _content = update_throughput_parameters - else: - _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") - - _request = build_update_gremlin_graph_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - graph_name=graph_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_update_gremlin_graph_throughput( - self, - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Gremlin graph. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param graph_name: Cosmos DB graph name. Required. - :type graph_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current Gremlin graph. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_update_gremlin_graph_throughput( - self, - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - update_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Gremlin graph. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param graph_name: Cosmos DB graph name. Required. - :type graph_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current Gremlin graph. Required. - :type update_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_update_gremlin_graph_throughput( - self, - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Gremlin graph. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param graph_name: Cosmos DB graph name. Required. - :type graph_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current Gremlin graph. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] type. - Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._update_gremlin_graph_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - graph_name=graph_name, - update_throughput_parameters=update_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _migrate_gremlin_graph_to_autoscale_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_gremlin_graph_to_autoscale_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - graph_name=graph_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_migrate_gremlin_graph_to_autoscale( - self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB Gremlin graph from manual throughput to autoscale. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param graph_name: Cosmos DB graph name. Required. - :type graph_name: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._migrate_gremlin_graph_to_autoscale_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - graph_name=graph_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _migrate_gremlin_graph_to_manual_throughput_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_gremlin_graph_to_manual_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - graph_name=graph_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_migrate_gremlin_graph_to_manual_throughput( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB Gremlin graph from autoscale to manual throughput. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param graph_name: Cosmos DB graph name. Required. - :type graph_name: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._migrate_gremlin_graph_to_manual_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - graph_name=graph_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _retrieve_continuous_backup_information_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(location, (IOBase, bytes)): - _content = location - else: - _json = self._serialize.body(location, "ContinuousBackupRestoreLocation") - - _request = build_retrieve_continuous_backup_information_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - graph_name=graph_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - location: _models.ContinuousBackupRestoreLocation, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.BackupInformation]: - """Retrieves continuous backup information for a gremlin graph. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param graph_name: Cosmos DB graph name. Required. - :type graph_name: str - :param location: The name of the continuous backup restore location. Required. - :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either BackupInformation or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - location: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.BackupInformation]: - """Retrieves continuous backup information for a gremlin graph. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param graph_name: Cosmos DB graph name. Required. - :type graph_name: str - :param location: The name of the continuous backup restore location. Required. - :type location: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either BackupInformation or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - graph_name: str, - location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.BackupInformation]: - """Retrieves continuous backup information for a gremlin graph. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param graph_name: Cosmos DB graph name. Required. - :type graph_name: str - :param location: The name of the continuous backup restore location. Is either a - ContinuousBackupRestoreLocation type or a IO[bytes] type. Required. - :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation or IO[bytes] - :return: An instance of LROPoller that returns either BackupInformation or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.BackupInformation] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._retrieve_continuous_backup_information_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - graph_name=graph_name, - location=location, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("BackupInformation", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.BackupInformation].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.BackupInformation]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_gremlin_databases_request( + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_gremlin_database_request( + resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_update_gremlin_database_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_gremlin_database_request( + resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_get_gremlin_database_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_gremlin_database_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_migrate_gremlin_database_to_autoscale_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToAutoscale", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_migrate_gremlin_database_to_manual_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToManualThroughput", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_gremlin_graphs_request( + resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_gremlin_graph_request( + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "graphName": _SERIALIZER.url("graph_name", graph_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_update_gremlin_graph_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "graphName": _SERIALIZER.url("graph_name", graph_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_gremlin_graph_request( + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "graphName": _SERIALIZER.url("graph_name", graph_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_get_gremlin_graph_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "graphName": _SERIALIZER.url("graph_name", graph_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_gremlin_graph_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "graphName": _SERIALIZER.url("graph_name", graph_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_migrate_gremlin_graph_to_autoscale_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToAutoscale", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "graphName": _SERIALIZER.url("graph_name", graph_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_migrate_gremlin_graph_to_manual_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToManualThroughput", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "graphName": _SERIALIZER.url("graph_name", graph_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_retrieve_continuous_backup_information_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/retrieveContinuousBackupInformation", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "graphName": _SERIALIZER.url("graph_name", graph_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class GremlinResourcesOperations: # pylint: disable=too-many-public-methods + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`gremlin_resources` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_gremlin_databases( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> Iterable["_models.GremlinDatabaseGetResults"]: + """Lists the Gremlin databases under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either GremlinDatabaseGetResults or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.GremlinDatabaseListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_gremlin_databases_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("GremlinDatabaseListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get_gremlin_database( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> _models.GremlinDatabaseGetResults: + """Gets the Gremlin databases under an existing Azure Cosmos DB database account with the provided + name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: GremlinDatabaseGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.GremlinDatabaseGetResults] = kwargs.pop("cls", None) + + _request = build_get_gremlin_database_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("GremlinDatabaseGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_update_gremlin_database_initial( + self, + resource_group_name: str, + account_name: str, + database_name: str, + create_update_gremlin_database_parameters: Union[_models.GremlinDatabaseCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_gremlin_database_parameters, (IOBase, bytes)): + _content = create_update_gremlin_database_parameters + else: + _json = self._serialize.body( + create_update_gremlin_database_parameters, "GremlinDatabaseCreateUpdateParameters" + ) + + _request = build_create_update_gremlin_database_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_update_gremlin_database( + self, + resource_group_name: str, + account_name: str, + database_name: str, + create_update_gremlin_database_parameters: _models.GremlinDatabaseCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.GremlinDatabaseGetResults]: + """Create or update an Azure Cosmos DB Gremlin database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param create_update_gremlin_database_parameters: The parameters to provide for the current + Gremlin database. Required. + :type create_update_gremlin_database_parameters: + ~azure.mgmt.cosmosdb.models.GremlinDatabaseCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either GremlinDatabaseGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_update_gremlin_database( + self, + resource_group_name: str, + account_name: str, + database_name: str, + create_update_gremlin_database_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.GremlinDatabaseGetResults]: + """Create or update an Azure Cosmos DB Gremlin database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param create_update_gremlin_database_parameters: The parameters to provide for the current + Gremlin database. Required. + :type create_update_gremlin_database_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either GremlinDatabaseGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_update_gremlin_database( + self, + resource_group_name: str, + account_name: str, + database_name: str, + create_update_gremlin_database_parameters: Union[_models.GremlinDatabaseCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.GremlinDatabaseGetResults]: + """Create or update an Azure Cosmos DB Gremlin database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param create_update_gremlin_database_parameters: The parameters to provide for the current + Gremlin database. Is either a GremlinDatabaseCreateUpdateParameters type or a IO[bytes] type. + Required. + :type create_update_gremlin_database_parameters: + ~azure.mgmt.cosmosdb.models.GremlinDatabaseCreateUpdateParameters or IO[bytes] + :return: An instance of LROPoller that returns either GremlinDatabaseGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.GremlinDatabaseGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_update_gremlin_database_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + create_update_gremlin_database_parameters=create_update_gremlin_database_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("GremlinDatabaseGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.GremlinDatabaseGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.GremlinDatabaseGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_gremlin_database_initial( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_gremlin_database_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete_gremlin_database( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Deletes an existing Azure Cosmos DB Gremlin database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_gremlin_database_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def get_gremlin_database_throughput( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> _models.ThroughputSettingsGetResults: + """Gets the RUs per second of the Gremlin database under an existing Azure Cosmos DB database + account with the provided name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: ThroughputSettingsGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + + _request = build_get_gremlin_database_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _update_gremlin_database_throughput_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(update_throughput_parameters, (IOBase, bytes)): + _content = update_throughput_parameters + else: + _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") + + _request = build_update_gremlin_database_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_update_gremlin_database_throughput( + self, + resource_group_name: str, + account_name: str, + database_name: str, + update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Gremlin database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current Gremlin database. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update_gremlin_database_throughput( + self, + resource_group_name: str, + account_name: str, + database_name: str, + update_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Gremlin database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current Gremlin database. Required. + :type update_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update_gremlin_database_throughput( + self, + resource_group_name: str, + account_name: str, + database_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Gremlin database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current Gremlin database. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] + type. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._update_gremlin_database_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + update_throughput_parameters=update_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _migrate_gremlin_database_to_autoscale_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_gremlin_database_to_autoscale_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_migrate_gremlin_database_to_autoscale( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB Gremlin database from manual throughput to autoscale. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._migrate_gremlin_database_to_autoscale_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _migrate_gremlin_database_to_manual_throughput_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_gremlin_database_to_manual_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_migrate_gremlin_database_to_manual_throughput( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB Gremlin database from autoscale to manual throughput. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._migrate_gremlin_database_to_manual_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def list_gremlin_graphs( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> Iterable["_models.GremlinGraphGetResults"]: + """Lists the Gremlin graph under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: An iterator like instance of either GremlinGraphGetResults or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.GremlinGraphGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.GremlinGraphListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_gremlin_graphs_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("GremlinGraphListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get_gremlin_graph( + self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any + ) -> _models.GremlinGraphGetResults: + """Gets the Gremlin graph under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param graph_name: Cosmos DB graph name. Required. + :type graph_name: str + :return: GremlinGraphGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.GremlinGraphGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.GremlinGraphGetResults] = kwargs.pop("cls", None) + + _request = build_get_gremlin_graph_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + graph_name=graph_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("GremlinGraphGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_update_gremlin_graph_initial( + self, + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + create_update_gremlin_graph_parameters: Union[_models.GremlinGraphCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_gremlin_graph_parameters, (IOBase, bytes)): + _content = create_update_gremlin_graph_parameters + else: + _json = self._serialize.body(create_update_gremlin_graph_parameters, "GremlinGraphCreateUpdateParameters") + + _request = build_create_update_gremlin_graph_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + graph_name=graph_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_update_gremlin_graph( + self, + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + create_update_gremlin_graph_parameters: _models.GremlinGraphCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.GremlinGraphGetResults]: + """Create or update an Azure Cosmos DB Gremlin graph. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param graph_name: Cosmos DB graph name. Required. + :type graph_name: str + :param create_update_gremlin_graph_parameters: The parameters to provide for the current + Gremlin graph. Required. + :type create_update_gremlin_graph_parameters: + ~azure.mgmt.cosmosdb.models.GremlinGraphCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either GremlinGraphGetResults or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinGraphGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_update_gremlin_graph( + self, + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + create_update_gremlin_graph_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.GremlinGraphGetResults]: + """Create or update an Azure Cosmos DB Gremlin graph. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param graph_name: Cosmos DB graph name. Required. + :type graph_name: str + :param create_update_gremlin_graph_parameters: The parameters to provide for the current + Gremlin graph. Required. + :type create_update_gremlin_graph_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either GremlinGraphGetResults or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinGraphGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_update_gremlin_graph( + self, + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + create_update_gremlin_graph_parameters: Union[_models.GremlinGraphCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.GremlinGraphGetResults]: + """Create or update an Azure Cosmos DB Gremlin graph. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param graph_name: Cosmos DB graph name. Required. + :type graph_name: str + :param create_update_gremlin_graph_parameters: The parameters to provide for the current + Gremlin graph. Is either a GremlinGraphCreateUpdateParameters type or a IO[bytes] type. + Required. + :type create_update_gremlin_graph_parameters: + ~azure.mgmt.cosmosdb.models.GremlinGraphCreateUpdateParameters or IO[bytes] + :return: An instance of LROPoller that returns either GremlinGraphGetResults or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinGraphGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.GremlinGraphGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_update_gremlin_graph_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + graph_name=graph_name, + create_update_gremlin_graph_parameters=create_update_gremlin_graph_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("GremlinGraphGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.GremlinGraphGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.GremlinGraphGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_gremlin_graph_initial( + self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_gremlin_graph_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + graph_name=graph_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete_gremlin_graph( + self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Deletes an existing Azure Cosmos DB Gremlin graph. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param graph_name: Cosmos DB graph name. Required. + :type graph_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_gremlin_graph_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + graph_name=graph_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def get_gremlin_graph_throughput( + self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any + ) -> _models.ThroughputSettingsGetResults: + """Gets the Gremlin graph throughput under an existing Azure Cosmos DB database account with the + provided name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param graph_name: Cosmos DB graph name. Required. + :type graph_name: str + :return: ThroughputSettingsGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + + _request = build_get_gremlin_graph_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + graph_name=graph_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _update_gremlin_graph_throughput_initial( + self, + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(update_throughput_parameters, (IOBase, bytes)): + _content = update_throughput_parameters + else: + _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") + + _request = build_update_gremlin_graph_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + graph_name=graph_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_update_gremlin_graph_throughput( + self, + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Gremlin graph. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param graph_name: Cosmos DB graph name. Required. + :type graph_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current Gremlin graph. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update_gremlin_graph_throughput( + self, + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + update_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Gremlin graph. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param graph_name: Cosmos DB graph name. Required. + :type graph_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current Gremlin graph. Required. + :type update_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update_gremlin_graph_throughput( + self, + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Gremlin graph. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param graph_name: Cosmos DB graph name. Required. + :type graph_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current Gremlin graph. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] type. + Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._update_gremlin_graph_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + graph_name=graph_name, + update_throughput_parameters=update_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _migrate_gremlin_graph_to_autoscale_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_gremlin_graph_to_autoscale_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + graph_name=graph_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_migrate_gremlin_graph_to_autoscale( + self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB Gremlin graph from manual throughput to autoscale. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param graph_name: Cosmos DB graph name. Required. + :type graph_name: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._migrate_gremlin_graph_to_autoscale_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + graph_name=graph_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _migrate_gremlin_graph_to_manual_throughput_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_gremlin_graph_to_manual_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + graph_name=graph_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_migrate_gremlin_graph_to_manual_throughput( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, graph_name: str, **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB Gremlin graph from autoscale to manual throughput. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param graph_name: Cosmos DB graph name. Required. + :type graph_name: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._migrate_gremlin_graph_to_manual_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + graph_name=graph_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _retrieve_continuous_backup_information_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(location, (IOBase, bytes)): + _content = location + else: + _json = self._serialize.body(location, "ContinuousBackupRestoreLocation") + + _request = build_retrieve_continuous_backup_information_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + graph_name=graph_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + location: _models.ContinuousBackupRestoreLocation, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.BackupInformation]: + """Retrieves continuous backup information for a gremlin graph. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param graph_name: Cosmos DB graph name. Required. + :type graph_name: str + :param location: The name of the continuous backup restore location. Required. + :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either BackupInformation or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + location: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.BackupInformation]: + """Retrieves continuous backup information for a gremlin graph. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param graph_name: Cosmos DB graph name. Required. + :type graph_name: str + :param location: The name of the continuous backup restore location. Required. + :type location: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either BackupInformation or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + graph_name: str, + location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.BackupInformation]: + """Retrieves continuous backup information for a gremlin graph. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param graph_name: Cosmos DB graph name. Required. + :type graph_name: str + :param location: The name of the continuous backup restore location. Is either a + ContinuousBackupRestoreLocation type or a IO[bytes] type. Required. + :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation or IO[bytes] + :return: An instance of LROPoller that returns either BackupInformation or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.BackupInformation] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._retrieve_continuous_backup_information_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + graph_name=graph_name, + location=location, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("BackupInformation", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.BackupInformation].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.BackupInformation]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_locations_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_locations_operations.py index c073f476fc1..e6adf89cb03 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_locations_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_locations_operations.py @@ -1,236 +1,236 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations") - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request(location: str, subscription_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}" - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "location": _SERIALIZER.url("location", location, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class LocationsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`locations` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list(self, **kwargs: Any) -> Iterable["_models.LocationGetResult"]: - """List Cosmos DB locations and their properties. - - :return: An iterator like instance of either LocationGetResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.LocationGetResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.LocationListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("LocationListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get(self, location: str, **kwargs: Any) -> _models.LocationGetResult: - """Get the properties of an existing Cosmos DB location. - - :param location: Cosmos DB region, with spaces between words and each word capitalized. - Required. - :type location: str - :return: LocationGetResult or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.LocationGetResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.LocationGetResult] = kwargs.pop("cls", None) - - _request = build_get_request( - location=location, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("LocationGetResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(location: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "location": _SERIALIZER.url("location", location, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class LocationsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`locations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.LocationGetResult"]: + """List Cosmos DB locations and their properties. + + :return: An iterator like instance of either LocationGetResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.LocationGetResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.LocationListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("LocationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get(self, location: str, **kwargs: Any) -> _models.LocationGetResult: + """Get the properties of an existing Cosmos DB location. + + :param location: Cosmos DB region, with spaces between words and each word capitalized. + Required. + :type location: str + :return: LocationGetResult or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.LocationGetResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.LocationGetResult] = kwargs.pop("cls", None) + + _request = build_get_request( + location=location, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("LocationGetResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_mongo_db_resources_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_mongo_db_resources_operations.py index 2d0683f9ffd..419a8324c2d 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_mongo_db_resources_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_mongo_db_resources_operations.py @@ -1,5822 +1,5822 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.arm_polling import ARMPolling - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_mongo_db_databases_request( - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_mongo_db_database_request( - resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_update_mongo_db_database_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_mongo_db_database_request( - resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) - - -def build_get_mongo_db_database_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/throughputSettings/default", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_update_mongo_db_database_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/throughputSettings/default", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_migrate_mongo_db_database_to_autoscale_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/throughputSettings/default/migrateToAutoscale", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_migrate_mongo_db_database_to_manual_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/throughputSettings/default/migrateToManualThroughput", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_mongo_db_database_retrieve_throughput_distribution_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/throughputSettings/default/retrieveThroughputDistribution", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_mongo_db_database_redistribute_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/throughputSettings/default/redistributeThroughput", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_mongo_db_container_retrieve_throughput_distribution_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}/throughputSettings/default/retrieveThroughputDistribution", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "collectionName": _SERIALIZER.url("collection_name", collection_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_mongo_db_container_redistribute_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}/throughputSettings/default/redistributeThroughput", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "collectionName": _SERIALIZER.url("collection_name", collection_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_mongo_db_collections_request( - resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_mongo_db_collection_request( - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "collectionName": _SERIALIZER.url("collection_name", collection_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_update_mongo_db_collection_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "collectionName": _SERIALIZER.url("collection_name", collection_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_mongo_db_collection_request( - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "collectionName": _SERIALIZER.url("collection_name", collection_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) - - -def build_mongo_db_database_partition_merge_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/partitionMerge", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_mongo_db_collection_partition_merge_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}/partitionMerge", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "collectionName": _SERIALIZER.url("collection_name", collection_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_mongo_db_collection_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}/throughputSettings/default", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "collectionName": _SERIALIZER.url("collection_name", collection_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_update_mongo_db_collection_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}/throughputSettings/default", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "collectionName": _SERIALIZER.url("collection_name", collection_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_migrate_mongo_db_collection_to_autoscale_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}/throughputSettings/default/migrateToAutoscale", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "collectionName": _SERIALIZER.url("collection_name", collection_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_migrate_mongo_db_collection_to_manual_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}/throughputSettings/default/migrateToManualThroughput", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "collectionName": _SERIALIZER.url("collection_name", collection_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_mongo_role_definition_request( - mongo_role_definition_id: str, resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbRoleDefinitions/{mongoRoleDefinitionId}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "mongoRoleDefinitionId": _SERIALIZER.url("mongo_role_definition_id", mongo_role_definition_id, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_update_mongo_role_definition_request( # pylint: disable=name-too-long - mongo_role_definition_id: str, resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbRoleDefinitions/{mongoRoleDefinitionId}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "mongoRoleDefinitionId": _SERIALIZER.url("mongo_role_definition_id", mongo_role_definition_id, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_mongo_role_definition_request( # pylint: disable=name-too-long - mongo_role_definition_id: str, resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbRoleDefinitions/{mongoRoleDefinitionId}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "mongoRoleDefinitionId": _SERIALIZER.url("mongo_role_definition_id", mongo_role_definition_id, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_mongo_role_definitions_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbRoleDefinitions", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_mongo_user_definition_request( - mongo_user_definition_id: str, resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbUserDefinitions/{mongoUserDefinitionId}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "mongoUserDefinitionId": _SERIALIZER.url("mongo_user_definition_id", mongo_user_definition_id, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_update_mongo_user_definition_request( # pylint: disable=name-too-long - mongo_user_definition_id: str, resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbUserDefinitions/{mongoUserDefinitionId}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "mongoUserDefinitionId": _SERIALIZER.url("mongo_user_definition_id", mongo_user_definition_id, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_mongo_user_definition_request( # pylint: disable=name-too-long - mongo_user_definition_id: str, resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbUserDefinitions/{mongoUserDefinitionId}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "mongoUserDefinitionId": _SERIALIZER.url("mongo_user_definition_id", mongo_user_definition_id, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_mongo_user_definitions_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbUserDefinitions", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_retrieve_continuous_backup_information_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}/retrieveContinuousBackupInformation", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "collectionName": _SERIALIZER.url("collection_name", collection_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -class MongoDBResourcesOperations: # pylint: disable=too-many-public-methods - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`mongo_db_resources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_mongo_db_databases( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> Iterable["_models.MongoDBDatabaseGetResults"]: - """Lists the MongoDB databases under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either MongoDBDatabaseGetResults or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MongoDBDatabaseListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_mongo_db_databases_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("MongoDBDatabaseListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get_mongo_db_database( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> _models.MongoDBDatabaseGetResults: - """Gets the MongoDB databases under an existing Azure Cosmos DB database account with the provided - name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: MongoDBDatabaseGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MongoDBDatabaseGetResults] = kwargs.pop("cls", None) - - _request = build_get_mongo_db_database_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("MongoDBDatabaseGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _create_update_mongo_db_database_initial( - self, - resource_group_name: str, - account_name: str, - database_name: str, - create_update_mongo_db_database_parameters: Union[_models.MongoDBDatabaseCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_mongo_db_database_parameters, (IOBase, bytes)): - _content = create_update_mongo_db_database_parameters - else: - _json = self._serialize.body( - create_update_mongo_db_database_parameters, "MongoDBDatabaseCreateUpdateParameters" - ) - - _request = build_create_update_mongo_db_database_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_update_mongo_db_database( - self, - resource_group_name: str, - account_name: str, - database_name: str, - create_update_mongo_db_database_parameters: _models.MongoDBDatabaseCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.MongoDBDatabaseGetResults]: - """Create or updates Azure Cosmos DB MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param create_update_mongo_db_database_parameters: The parameters to provide for the current - MongoDB database. Required. - :type create_update_mongo_db_database_parameters: - ~azure.mgmt.cosmosdb.models.MongoDBDatabaseCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either MongoDBDatabaseGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_update_mongo_db_database( - self, - resource_group_name: str, - account_name: str, - database_name: str, - create_update_mongo_db_database_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.MongoDBDatabaseGetResults]: - """Create or updates Azure Cosmos DB MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param create_update_mongo_db_database_parameters: The parameters to provide for the current - MongoDB database. Required. - :type create_update_mongo_db_database_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either MongoDBDatabaseGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_update_mongo_db_database( - self, - resource_group_name: str, - account_name: str, - database_name: str, - create_update_mongo_db_database_parameters: Union[_models.MongoDBDatabaseCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.MongoDBDatabaseGetResults]: - """Create or updates Azure Cosmos DB MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param create_update_mongo_db_database_parameters: The parameters to provide for the current - MongoDB database. Is either a MongoDBDatabaseCreateUpdateParameters type or a IO[bytes] type. - Required. - :type create_update_mongo_db_database_parameters: - ~azure.mgmt.cosmosdb.models.MongoDBDatabaseCreateUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either MongoDBDatabaseGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.MongoDBDatabaseGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_update_mongo_db_database_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - create_update_mongo_db_database_parameters=create_update_mongo_db_database_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("MongoDBDatabaseGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.MongoDBDatabaseGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.MongoDBDatabaseGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _delete_mongo_db_database_initial( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_mongo_db_database_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete_mongo_db_database( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> LROPoller[None]: - """Deletes an existing Azure Cosmos DB MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_mongo_db_database_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace - def get_mongo_db_database_throughput( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> _models.ThroughputSettingsGetResults: - """Gets the RUs per second of the MongoDB database under an existing Azure Cosmos DB database - account with the provided name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: ThroughputSettingsGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - - _request = build_get_mongo_db_database_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _update_mongo_db_database_throughput_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(update_throughput_parameters, (IOBase, bytes)): - _content = update_throughput_parameters - else: - _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") - - _request = build_update_mongo_db_database_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_update_mongo_db_database_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of the an Azure Cosmos DB MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current MongoDB database. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_update_mongo_db_database_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - update_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of the an Azure Cosmos DB MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current MongoDB database. Required. - :type update_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_update_mongo_db_database_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of the an Azure Cosmos DB MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current MongoDB database. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] - type. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._update_mongo_db_database_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - update_throughput_parameters=update_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _migrate_mongo_db_database_to_autoscale_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_mongo_db_database_to_autoscale_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_migrate_mongo_db_database_to_autoscale( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB MongoDB database from manual throughput to autoscale. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._migrate_mongo_db_database_to_autoscale_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _migrate_mongo_db_database_to_manual_throughput_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_mongo_db_database_to_manual_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_migrate_mongo_db_database_to_manual_throughput( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB MongoDB database from autoscale to manual throughput. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._migrate_mongo_db_database_to_manual_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _mongo_db_database_retrieve_throughput_distribution_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(retrieve_throughput_parameters, (IOBase, bytes)): - _content = retrieve_throughput_parameters - else: - _json = self._serialize.body(retrieve_throughput_parameters, "RetrieveThroughputParameters") - - _request = build_mongo_db_database_retrieve_throughput_distribution_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_mongo_db_database_retrieve_throughput_distribution( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - retrieve_throughput_parameters: _models.RetrieveThroughputParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Retrieve throughput distribution for an Azure Cosmos DB MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput - distribution for the current MongoDB database. Required. - :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_mongo_db_database_retrieve_throughput_distribution( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - retrieve_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Retrieve throughput distribution for an Azure Cosmos DB MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput - distribution for the current MongoDB database. Required. - :type retrieve_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_mongo_db_database_retrieve_throughput_distribution( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Retrieve throughput distribution for an Azure Cosmos DB MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput - distribution for the current MongoDB database. Is either a RetrieveThroughputParameters type or - a IO[bytes] type. Required. - :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters - or IO[bytes] - :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._mongo_db_database_retrieve_throughput_distribution_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - retrieve_throughput_parameters=retrieve_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.PhysicalPartitionThroughputInfoResult]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _mongo_db_database_redistribute_throughput_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(redistribute_throughput_parameters, (IOBase, bytes)): - _content = redistribute_throughput_parameters - else: - _json = self._serialize.body(redistribute_throughput_parameters, "RedistributeThroughputParameters") - - _request = build_mongo_db_database_redistribute_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_mongo_db_database_redistribute_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - redistribute_throughput_parameters: _models.RedistributeThroughputParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Redistribute throughput for an Azure Cosmos DB MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param redistribute_throughput_parameters: The parameters to provide for redistributing - throughput for the current MongoDB database. Required. - :type redistribute_throughput_parameters: - ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_mongo_db_database_redistribute_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - redistribute_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Redistribute throughput for an Azure Cosmos DB MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param redistribute_throughput_parameters: The parameters to provide for redistributing - throughput for the current MongoDB database. Required. - :type redistribute_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_mongo_db_database_redistribute_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Redistribute throughput for an Azure Cosmos DB MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param redistribute_throughput_parameters: The parameters to provide for redistributing - throughput for the current MongoDB database. Is either a RedistributeThroughputParameters type - or a IO[bytes] type. Required. - :type redistribute_throughput_parameters: - ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters or IO[bytes] - :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._mongo_db_database_redistribute_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - redistribute_throughput_parameters=redistribute_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.PhysicalPartitionThroughputInfoResult]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _mongo_db_container_retrieve_throughput_distribution_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(retrieve_throughput_parameters, (IOBase, bytes)): - _content = retrieve_throughput_parameters - else: - _json = self._serialize.body(retrieve_throughput_parameters, "RetrieveThroughputParameters") - - _request = build_mongo_db_container_retrieve_throughput_distribution_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_mongo_db_container_retrieve_throughput_distribution( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - retrieve_throughput_parameters: _models.RetrieveThroughputParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Retrieve throughput distribution for an Azure Cosmos DB MongoDB container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput - distribution for the current MongoDB container. Required. - :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_mongo_db_container_retrieve_throughput_distribution( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - retrieve_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Retrieve throughput distribution for an Azure Cosmos DB MongoDB container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput - distribution for the current MongoDB container. Required. - :type retrieve_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_mongo_db_container_retrieve_throughput_distribution( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Retrieve throughput distribution for an Azure Cosmos DB MongoDB container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput - distribution for the current MongoDB container. Is either a RetrieveThroughputParameters type - or a IO[bytes] type. Required. - :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters - or IO[bytes] - :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._mongo_db_container_retrieve_throughput_distribution_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - retrieve_throughput_parameters=retrieve_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.PhysicalPartitionThroughputInfoResult]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _mongo_db_container_redistribute_throughput_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(redistribute_throughput_parameters, (IOBase, bytes)): - _content = redistribute_throughput_parameters - else: - _json = self._serialize.body(redistribute_throughput_parameters, "RedistributeThroughputParameters") - - _request = build_mongo_db_container_redistribute_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_mongo_db_container_redistribute_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - redistribute_throughput_parameters: _models.RedistributeThroughputParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Redistribute throughput for an Azure Cosmos DB MongoDB container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param redistribute_throughput_parameters: The parameters to provide for redistributing - throughput for the current MongoDB container. Required. - :type redistribute_throughput_parameters: - ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_mongo_db_container_redistribute_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - redistribute_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Redistribute throughput for an Azure Cosmos DB MongoDB container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param redistribute_throughput_parameters: The parameters to provide for redistributing - throughput for the current MongoDB container. Required. - :type redistribute_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_mongo_db_container_redistribute_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Redistribute throughput for an Azure Cosmos DB MongoDB container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param redistribute_throughput_parameters: The parameters to provide for redistributing - throughput for the current MongoDB container. Is either a RedistributeThroughputParameters type - or a IO[bytes] type. Required. - :type redistribute_throughput_parameters: - ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters or IO[bytes] - :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._mongo_db_container_redistribute_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - redistribute_throughput_parameters=redistribute_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.PhysicalPartitionThroughputInfoResult]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @distributed_trace - def list_mongo_db_collections( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> Iterable["_models.MongoDBCollectionGetResults"]: - """Lists the MongoDB collection under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: An iterator like instance of either MongoDBCollectionGetResults or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.MongoDBCollectionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MongoDBCollectionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_mongo_db_collections_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("MongoDBCollectionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get_mongo_db_collection( - self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any - ) -> _models.MongoDBCollectionGetResults: - """Gets the MongoDB collection under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :return: MongoDBCollectionGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.MongoDBCollectionGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MongoDBCollectionGetResults] = kwargs.pop("cls", None) - - _request = build_get_mongo_db_collection_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("MongoDBCollectionGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _create_update_mongo_db_collection_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - create_update_mongo_db_collection_parameters: Union[_models.MongoDBCollectionCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_mongo_db_collection_parameters, (IOBase, bytes)): - _content = create_update_mongo_db_collection_parameters - else: - _json = self._serialize.body( - create_update_mongo_db_collection_parameters, "MongoDBCollectionCreateUpdateParameters" - ) - - _request = build_create_update_mongo_db_collection_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_update_mongo_db_collection( - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - create_update_mongo_db_collection_parameters: _models.MongoDBCollectionCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.MongoDBCollectionGetResults]: - """Create or update an Azure Cosmos DB MongoDB Collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param create_update_mongo_db_collection_parameters: The parameters to provide for the current - MongoDB Collection. Required. - :type create_update_mongo_db_collection_parameters: - ~azure.mgmt.cosmosdb.models.MongoDBCollectionCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either MongoDBCollectionGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.MongoDBCollectionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_update_mongo_db_collection( - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - create_update_mongo_db_collection_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.MongoDBCollectionGetResults]: - """Create or update an Azure Cosmos DB MongoDB Collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param create_update_mongo_db_collection_parameters: The parameters to provide for the current - MongoDB Collection. Required. - :type create_update_mongo_db_collection_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either MongoDBCollectionGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.MongoDBCollectionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_update_mongo_db_collection( - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - create_update_mongo_db_collection_parameters: Union[_models.MongoDBCollectionCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.MongoDBCollectionGetResults]: - """Create or update an Azure Cosmos DB MongoDB Collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param create_update_mongo_db_collection_parameters: The parameters to provide for the current - MongoDB Collection. Is either a MongoDBCollectionCreateUpdateParameters type or a IO[bytes] - type. Required. - :type create_update_mongo_db_collection_parameters: - ~azure.mgmt.cosmosdb.models.MongoDBCollectionCreateUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either MongoDBCollectionGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.MongoDBCollectionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.MongoDBCollectionGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_update_mongo_db_collection_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - create_update_mongo_db_collection_parameters=create_update_mongo_db_collection_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("MongoDBCollectionGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.MongoDBCollectionGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.MongoDBCollectionGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _delete_mongo_db_collection_initial( - self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_mongo_db_collection_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete_mongo_db_collection( - self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any - ) -> LROPoller[None]: - """Deletes an existing Azure Cosmos DB MongoDB Collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_mongo_db_collection_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - def _mongo_db_database_partition_merge_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - merge_parameters: Union[_models.MergeParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(merge_parameters, (IOBase, bytes)): - _content = merge_parameters - else: - _json = self._serialize.body(merge_parameters, "MergeParameters") - - _request = build_mongo_db_database_partition_merge_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_mongo_db_database_partition_merge( - self, - resource_group_name: str, - account_name: str, - database_name: str, - merge_parameters: _models.MergeParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionStorageInfoCollection]: - """Merges the partitions of a MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param merge_parameters: The parameters for the merge operation. Required. - :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either PhysicalPartitionStorageInfoCollection or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_mongo_db_database_partition_merge( - self, - resource_group_name: str, - account_name: str, - database_name: str, - merge_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionStorageInfoCollection]: - """Merges the partitions of a MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param merge_parameters: The parameters for the merge operation. Required. - :type merge_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either PhysicalPartitionStorageInfoCollection or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_mongo_db_database_partition_merge( - self, - resource_group_name: str, - account_name: str, - database_name: str, - merge_parameters: Union[_models.MergeParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionStorageInfoCollection]: - """Merges the partitions of a MongoDB database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param merge_parameters: The parameters for the merge operation. Is either a MergeParameters - type or a IO[bytes] type. Required. - :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters or IO[bytes] - :return: An instance of LROPoller that returns either PhysicalPartitionStorageInfoCollection or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PhysicalPartitionStorageInfoCollection] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._mongo_db_database_partition_merge_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - merge_parameters=merge_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("PhysicalPartitionStorageInfoCollection", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.PhysicalPartitionStorageInfoCollection].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.PhysicalPartitionStorageInfoCollection]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _list_mongo_db_collection_partition_merge_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - merge_parameters: Union[_models.MergeParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(merge_parameters, (IOBase, bytes)): - _content = merge_parameters - else: - _json = self._serialize.body(merge_parameters, "MergeParameters") - - _request = build_list_mongo_db_collection_partition_merge_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_list_mongo_db_collection_partition_merge( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - merge_parameters: _models.MergeParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionStorageInfoCollection]: - """Merges the partitions of a MongoDB Collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param merge_parameters: The parameters for the merge operation. Required. - :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either PhysicalPartitionStorageInfoCollection or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_list_mongo_db_collection_partition_merge( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - merge_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionStorageInfoCollection]: - """Merges the partitions of a MongoDB Collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param merge_parameters: The parameters for the merge operation. Required. - :type merge_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either PhysicalPartitionStorageInfoCollection or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_list_mongo_db_collection_partition_merge( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - merge_parameters: Union[_models.MergeParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionStorageInfoCollection]: - """Merges the partitions of a MongoDB Collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param merge_parameters: The parameters for the merge operation. Is either a MergeParameters - type or a IO[bytes] type. Required. - :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters or IO[bytes] - :return: An instance of LROPoller that returns either PhysicalPartitionStorageInfoCollection or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PhysicalPartitionStorageInfoCollection] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._list_mongo_db_collection_partition_merge_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - merge_parameters=merge_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("PhysicalPartitionStorageInfoCollection", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.PhysicalPartitionStorageInfoCollection].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.PhysicalPartitionStorageInfoCollection]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @distributed_trace - def get_mongo_db_collection_throughput( - self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any - ) -> _models.ThroughputSettingsGetResults: - """Gets the RUs per second of the MongoDB collection under an existing Azure Cosmos DB database - account with the provided name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :return: ThroughputSettingsGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - - _request = build_get_mongo_db_collection_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _update_mongo_db_collection_throughput_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(update_throughput_parameters, (IOBase, bytes)): - _content = update_throughput_parameters - else: - _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") - - _request = build_update_mongo_db_collection_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_update_mongo_db_collection_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Update the RUs per second of an Azure Cosmos DB MongoDB collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current MongoDB collection. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_update_mongo_db_collection_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - update_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Update the RUs per second of an Azure Cosmos DB MongoDB collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current MongoDB collection. Required. - :type update_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_update_mongo_db_collection_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Update the RUs per second of an Azure Cosmos DB MongoDB collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param update_throughput_parameters: The RUs per second of the parameters to provide for the - current MongoDB collection. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] - type. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._update_mongo_db_collection_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - update_throughput_parameters=update_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _migrate_mongo_db_collection_to_autoscale_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_mongo_db_collection_to_autoscale_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_migrate_mongo_db_collection_to_autoscale( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB MongoDB collection from manual throughput to autoscale. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._migrate_mongo_db_collection_to_autoscale_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _migrate_mongo_db_collection_to_manual_throughput_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_mongo_db_collection_to_manual_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_migrate_mongo_db_collection_to_manual_throughput( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB MongoDB collection from autoscale to manual throughput. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._migrate_mongo_db_collection_to_manual_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @distributed_trace - def get_mongo_role_definition( - self, mongo_role_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any - ) -> _models.MongoRoleDefinitionGetResults: - """Retrieves the properties of an existing Azure Cosmos DB Mongo Role Definition with the given - Id. - - :param mongo_role_definition_id: The ID for the Role Definition {dbName.roleName}. Required. - :type mongo_role_definition_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: MongoRoleDefinitionGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.MongoRoleDefinitionGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MongoRoleDefinitionGetResults] = kwargs.pop("cls", None) - - _request = build_get_mongo_role_definition_request( - mongo_role_definition_id=mongo_role_definition_id, - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("MongoRoleDefinitionGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _create_update_mongo_role_definition_initial( # pylint: disable=name-too-long - self, - mongo_role_definition_id: str, - resource_group_name: str, - account_name: str, - create_update_mongo_role_definition_parameters: Union[ - _models.MongoRoleDefinitionCreateUpdateParameters, IO[bytes] - ], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_mongo_role_definition_parameters, (IOBase, bytes)): - _content = create_update_mongo_role_definition_parameters - else: - _json = self._serialize.body( - create_update_mongo_role_definition_parameters, "MongoRoleDefinitionCreateUpdateParameters" - ) - - _request = build_create_update_mongo_role_definition_request( - mongo_role_definition_id=mongo_role_definition_id, - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_update_mongo_role_definition( # pylint: disable=name-too-long - self, - mongo_role_definition_id: str, - resource_group_name: str, - account_name: str, - create_update_mongo_role_definition_parameters: _models.MongoRoleDefinitionCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.MongoRoleDefinitionGetResults]: - """Creates or updates an Azure Cosmos DB Mongo Role Definition. - - :param mongo_role_definition_id: The ID for the Role Definition {dbName.roleName}. Required. - :type mongo_role_definition_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param create_update_mongo_role_definition_parameters: The properties required to create or - update a Role Definition. Required. - :type create_update_mongo_role_definition_parameters: - ~azure.mgmt.cosmosdb.models.MongoRoleDefinitionCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either MongoRoleDefinitionGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.MongoRoleDefinitionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_update_mongo_role_definition( # pylint: disable=name-too-long - self, - mongo_role_definition_id: str, - resource_group_name: str, - account_name: str, - create_update_mongo_role_definition_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.MongoRoleDefinitionGetResults]: - """Creates or updates an Azure Cosmos DB Mongo Role Definition. - - :param mongo_role_definition_id: The ID for the Role Definition {dbName.roleName}. Required. - :type mongo_role_definition_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param create_update_mongo_role_definition_parameters: The properties required to create or - update a Role Definition. Required. - :type create_update_mongo_role_definition_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either MongoRoleDefinitionGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.MongoRoleDefinitionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_update_mongo_role_definition( # pylint: disable=name-too-long - self, - mongo_role_definition_id: str, - resource_group_name: str, - account_name: str, - create_update_mongo_role_definition_parameters: Union[ - _models.MongoRoleDefinitionCreateUpdateParameters, IO[bytes] - ], - **kwargs: Any - ) -> LROPoller[_models.MongoRoleDefinitionGetResults]: - """Creates or updates an Azure Cosmos DB Mongo Role Definition. - - :param mongo_role_definition_id: The ID for the Role Definition {dbName.roleName}. Required. - :type mongo_role_definition_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param create_update_mongo_role_definition_parameters: The properties required to create or - update a Role Definition. Is either a MongoRoleDefinitionCreateUpdateParameters type or a - IO[bytes] type. Required. - :type create_update_mongo_role_definition_parameters: - ~azure.mgmt.cosmosdb.models.MongoRoleDefinitionCreateUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either MongoRoleDefinitionGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.MongoRoleDefinitionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.MongoRoleDefinitionGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_update_mongo_role_definition_initial( - mongo_role_definition_id=mongo_role_definition_id, - resource_group_name=resource_group_name, - account_name=account_name, - create_update_mongo_role_definition_parameters=create_update_mongo_role_definition_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("MongoRoleDefinitionGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.MongoRoleDefinitionGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.MongoRoleDefinitionGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _delete_mongo_role_definition_initial( - self, mongo_role_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_mongo_role_definition_request( - mongo_role_definition_id=mongo_role_definition_id, - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202, 204]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete_mongo_role_definition( - self, mongo_role_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any - ) -> LROPoller[None]: - """Deletes an existing Azure Cosmos DB Mongo Role Definition. - - :param mongo_role_definition_id: The ID for the Role Definition {dbName.roleName}. Required. - :type mongo_role_definition_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_mongo_role_definition_initial( - mongo_role_definition_id=mongo_role_definition_id, - resource_group_name=resource_group_name, - account_name=account_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace - def list_mongo_role_definitions( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> Iterable["_models.MongoRoleDefinitionGetResults"]: - """Retrieves the list of all Azure Cosmos DB Mongo Role Definitions. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either MongoRoleDefinitionGetResults or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.MongoRoleDefinitionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MongoRoleDefinitionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_mongo_role_definitions_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("MongoRoleDefinitionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get_mongo_user_definition( - self, mongo_user_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any - ) -> _models.MongoUserDefinitionGetResults: - """Retrieves the properties of an existing Azure Cosmos DB Mongo User Definition with the given - Id. - - :param mongo_user_definition_id: The ID for the User Definition {dbName.userName}. Required. - :type mongo_user_definition_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: MongoUserDefinitionGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.MongoUserDefinitionGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MongoUserDefinitionGetResults] = kwargs.pop("cls", None) - - _request = build_get_mongo_user_definition_request( - mongo_user_definition_id=mongo_user_definition_id, - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("MongoUserDefinitionGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _create_update_mongo_user_definition_initial( # pylint: disable=name-too-long - self, - mongo_user_definition_id: str, - resource_group_name: str, - account_name: str, - create_update_mongo_user_definition_parameters: Union[ - _models.MongoUserDefinitionCreateUpdateParameters, IO[bytes] - ], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_mongo_user_definition_parameters, (IOBase, bytes)): - _content = create_update_mongo_user_definition_parameters - else: - _json = self._serialize.body( - create_update_mongo_user_definition_parameters, "MongoUserDefinitionCreateUpdateParameters" - ) - - _request = build_create_update_mongo_user_definition_request( - mongo_user_definition_id=mongo_user_definition_id, - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_update_mongo_user_definition( # pylint: disable=name-too-long - self, - mongo_user_definition_id: str, - resource_group_name: str, - account_name: str, - create_update_mongo_user_definition_parameters: _models.MongoUserDefinitionCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.MongoUserDefinitionGetResults]: - """Creates or updates an Azure Cosmos DB Mongo User Definition. - - :param mongo_user_definition_id: The ID for the User Definition {dbName.userName}. Required. - :type mongo_user_definition_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param create_update_mongo_user_definition_parameters: The properties required to create or - update a User Definition. Required. - :type create_update_mongo_user_definition_parameters: - ~azure.mgmt.cosmosdb.models.MongoUserDefinitionCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either MongoUserDefinitionGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.MongoUserDefinitionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_update_mongo_user_definition( # pylint: disable=name-too-long - self, - mongo_user_definition_id: str, - resource_group_name: str, - account_name: str, - create_update_mongo_user_definition_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.MongoUserDefinitionGetResults]: - """Creates or updates an Azure Cosmos DB Mongo User Definition. - - :param mongo_user_definition_id: The ID for the User Definition {dbName.userName}. Required. - :type mongo_user_definition_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param create_update_mongo_user_definition_parameters: The properties required to create or - update a User Definition. Required. - :type create_update_mongo_user_definition_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either MongoUserDefinitionGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.MongoUserDefinitionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_update_mongo_user_definition( # pylint: disable=name-too-long - self, - mongo_user_definition_id: str, - resource_group_name: str, - account_name: str, - create_update_mongo_user_definition_parameters: Union[ - _models.MongoUserDefinitionCreateUpdateParameters, IO[bytes] - ], - **kwargs: Any - ) -> LROPoller[_models.MongoUserDefinitionGetResults]: - """Creates or updates an Azure Cosmos DB Mongo User Definition. - - :param mongo_user_definition_id: The ID for the User Definition {dbName.userName}. Required. - :type mongo_user_definition_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param create_update_mongo_user_definition_parameters: The properties required to create or - update a User Definition. Is either a MongoUserDefinitionCreateUpdateParameters type or a - IO[bytes] type. Required. - :type create_update_mongo_user_definition_parameters: - ~azure.mgmt.cosmosdb.models.MongoUserDefinitionCreateUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either MongoUserDefinitionGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.MongoUserDefinitionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.MongoUserDefinitionGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_update_mongo_user_definition_initial( - mongo_user_definition_id=mongo_user_definition_id, - resource_group_name=resource_group_name, - account_name=account_name, - create_update_mongo_user_definition_parameters=create_update_mongo_user_definition_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("MongoUserDefinitionGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.MongoUserDefinitionGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.MongoUserDefinitionGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _delete_mongo_user_definition_initial( - self, mongo_user_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_mongo_user_definition_request( - mongo_user_definition_id=mongo_user_definition_id, - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202, 204]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete_mongo_user_definition( - self, mongo_user_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any - ) -> LROPoller[None]: - """Deletes an existing Azure Cosmos DB Mongo User Definition. - - :param mongo_user_definition_id: The ID for the User Definition {dbName.userName}. Required. - :type mongo_user_definition_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_mongo_user_definition_initial( - mongo_user_definition_id=mongo_user_definition_id, - resource_group_name=resource_group_name, - account_name=account_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace - def list_mongo_user_definitions( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> Iterable["_models.MongoUserDefinitionGetResults"]: - """Retrieves the list of all Azure Cosmos DB Mongo User Definition. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either MongoUserDefinitionGetResults or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.MongoUserDefinitionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.MongoUserDefinitionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_mongo_user_definitions_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("MongoUserDefinitionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - def _retrieve_continuous_backup_information_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(location, (IOBase, bytes)): - _content = location - else: - _json = self._serialize.body(location, "ContinuousBackupRestoreLocation") - - _request = build_retrieve_continuous_backup_information_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - location: _models.ContinuousBackupRestoreLocation, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.BackupInformation]: - """Retrieves continuous backup information for a Mongodb collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param location: The name of the continuous backup restore location. Required. - :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either BackupInformation or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - location: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.BackupInformation]: - """Retrieves continuous backup information for a Mongodb collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param location: The name of the continuous backup restore location. Required. - :type location: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either BackupInformation or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - collection_name: str, - location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.BackupInformation]: - """Retrieves continuous backup information for a Mongodb collection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param collection_name: Cosmos DB collection name. Required. - :type collection_name: str - :param location: The name of the continuous backup restore location. Is either a - ContinuousBackupRestoreLocation type or a IO[bytes] type. Required. - :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation or IO[bytes] - :return: An instance of LROPoller that returns either BackupInformation or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.BackupInformation] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._retrieve_continuous_backup_information_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - collection_name=collection_name, - location=location, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("BackupInformation", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.BackupInformation].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.BackupInformation]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_mongo_db_databases_request( + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_mongo_db_database_request( + resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_update_mongo_db_database_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_mongo_db_database_request( + resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_get_mongo_db_database_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/throughputSettings/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_mongo_db_database_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/throughputSettings/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_migrate_mongo_db_database_to_autoscale_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/throughputSettings/default/migrateToAutoscale", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_migrate_mongo_db_database_to_manual_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/throughputSettings/default/migrateToManualThroughput", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_mongo_db_database_retrieve_throughput_distribution_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/throughputSettings/default/retrieveThroughputDistribution", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_mongo_db_database_redistribute_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/throughputSettings/default/redistributeThroughput", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_mongo_db_container_retrieve_throughput_distribution_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}/throughputSettings/default/retrieveThroughputDistribution", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "collectionName": _SERIALIZER.url("collection_name", collection_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_mongo_db_container_redistribute_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}/throughputSettings/default/redistributeThroughput", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "collectionName": _SERIALIZER.url("collection_name", collection_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_mongo_db_collections_request( + resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_mongo_db_collection_request( + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "collectionName": _SERIALIZER.url("collection_name", collection_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_update_mongo_db_collection_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "collectionName": _SERIALIZER.url("collection_name", collection_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_mongo_db_collection_request( + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "collectionName": _SERIALIZER.url("collection_name", collection_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_mongo_db_database_partition_merge_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/partitionMerge", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_mongo_db_collection_partition_merge_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}/partitionMerge", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "collectionName": _SERIALIZER.url("collection_name", collection_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_mongo_db_collection_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}/throughputSettings/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "collectionName": _SERIALIZER.url("collection_name", collection_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_mongo_db_collection_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}/throughputSettings/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "collectionName": _SERIALIZER.url("collection_name", collection_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_migrate_mongo_db_collection_to_autoscale_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}/throughputSettings/default/migrateToAutoscale", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "collectionName": _SERIALIZER.url("collection_name", collection_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_migrate_mongo_db_collection_to_manual_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}/throughputSettings/default/migrateToManualThroughput", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "collectionName": _SERIALIZER.url("collection_name", collection_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_mongo_role_definition_request( + mongo_role_definition_id: str, resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbRoleDefinitions/{mongoRoleDefinitionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "mongoRoleDefinitionId": _SERIALIZER.url("mongo_role_definition_id", mongo_role_definition_id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_update_mongo_role_definition_request( # pylint: disable=name-too-long + mongo_role_definition_id: str, resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbRoleDefinitions/{mongoRoleDefinitionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "mongoRoleDefinitionId": _SERIALIZER.url("mongo_role_definition_id", mongo_role_definition_id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_mongo_role_definition_request( # pylint: disable=name-too-long + mongo_role_definition_id: str, resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbRoleDefinitions/{mongoRoleDefinitionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "mongoRoleDefinitionId": _SERIALIZER.url("mongo_role_definition_id", mongo_role_definition_id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_mongo_role_definitions_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbRoleDefinitions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_mongo_user_definition_request( + mongo_user_definition_id: str, resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbUserDefinitions/{mongoUserDefinitionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "mongoUserDefinitionId": _SERIALIZER.url("mongo_user_definition_id", mongo_user_definition_id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_update_mongo_user_definition_request( # pylint: disable=name-too-long + mongo_user_definition_id: str, resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbUserDefinitions/{mongoUserDefinitionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "mongoUserDefinitionId": _SERIALIZER.url("mongo_user_definition_id", mongo_user_definition_id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_mongo_user_definition_request( # pylint: disable=name-too-long + mongo_user_definition_id: str, resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbUserDefinitions/{mongoUserDefinitionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "mongoUserDefinitionId": _SERIALIZER.url("mongo_user_definition_id", mongo_user_definition_id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_mongo_user_definitions_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbUserDefinitions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_retrieve_continuous_backup_information_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}/retrieveContinuousBackupInformation", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "collectionName": _SERIALIZER.url("collection_name", collection_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class MongoDBResourcesOperations: # pylint: disable=too-many-public-methods + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`mongo_db_resources` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_mongo_db_databases( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> Iterable["_models.MongoDBDatabaseGetResults"]: + """Lists the MongoDB databases under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either MongoDBDatabaseGetResults or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MongoDBDatabaseListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_mongo_db_databases_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("MongoDBDatabaseListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get_mongo_db_database( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> _models.MongoDBDatabaseGetResults: + """Gets the MongoDB databases under an existing Azure Cosmos DB database account with the provided + name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: MongoDBDatabaseGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MongoDBDatabaseGetResults] = kwargs.pop("cls", None) + + _request = build_get_mongo_db_database_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("MongoDBDatabaseGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_update_mongo_db_database_initial( + self, + resource_group_name: str, + account_name: str, + database_name: str, + create_update_mongo_db_database_parameters: Union[_models.MongoDBDatabaseCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_mongo_db_database_parameters, (IOBase, bytes)): + _content = create_update_mongo_db_database_parameters + else: + _json = self._serialize.body( + create_update_mongo_db_database_parameters, "MongoDBDatabaseCreateUpdateParameters" + ) + + _request = build_create_update_mongo_db_database_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_update_mongo_db_database( + self, + resource_group_name: str, + account_name: str, + database_name: str, + create_update_mongo_db_database_parameters: _models.MongoDBDatabaseCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.MongoDBDatabaseGetResults]: + """Create or updates Azure Cosmos DB MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param create_update_mongo_db_database_parameters: The parameters to provide for the current + MongoDB database. Required. + :type create_update_mongo_db_database_parameters: + ~azure.mgmt.cosmosdb.models.MongoDBDatabaseCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either MongoDBDatabaseGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_update_mongo_db_database( + self, + resource_group_name: str, + account_name: str, + database_name: str, + create_update_mongo_db_database_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.MongoDBDatabaseGetResults]: + """Create or updates Azure Cosmos DB MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param create_update_mongo_db_database_parameters: The parameters to provide for the current + MongoDB database. Required. + :type create_update_mongo_db_database_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either MongoDBDatabaseGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_update_mongo_db_database( + self, + resource_group_name: str, + account_name: str, + database_name: str, + create_update_mongo_db_database_parameters: Union[_models.MongoDBDatabaseCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.MongoDBDatabaseGetResults]: + """Create or updates Azure Cosmos DB MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param create_update_mongo_db_database_parameters: The parameters to provide for the current + MongoDB database. Is either a MongoDBDatabaseCreateUpdateParameters type or a IO[bytes] type. + Required. + :type create_update_mongo_db_database_parameters: + ~azure.mgmt.cosmosdb.models.MongoDBDatabaseCreateUpdateParameters or IO[bytes] + :return: An instance of LROPoller that returns either MongoDBDatabaseGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.MongoDBDatabaseGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_update_mongo_db_database_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + create_update_mongo_db_database_parameters=create_update_mongo_db_database_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("MongoDBDatabaseGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.MongoDBDatabaseGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.MongoDBDatabaseGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_mongo_db_database_initial( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_mongo_db_database_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete_mongo_db_database( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Deletes an existing Azure Cosmos DB MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_mongo_db_database_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def get_mongo_db_database_throughput( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> _models.ThroughputSettingsGetResults: + """Gets the RUs per second of the MongoDB database under an existing Azure Cosmos DB database + account with the provided name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: ThroughputSettingsGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + + _request = build_get_mongo_db_database_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _update_mongo_db_database_throughput_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(update_throughput_parameters, (IOBase, bytes)): + _content = update_throughput_parameters + else: + _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") + + _request = build_update_mongo_db_database_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_update_mongo_db_database_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of the an Azure Cosmos DB MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current MongoDB database. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update_mongo_db_database_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + update_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of the an Azure Cosmos DB MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current MongoDB database. Required. + :type update_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update_mongo_db_database_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of the an Azure Cosmos DB MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current MongoDB database. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] + type. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._update_mongo_db_database_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + update_throughput_parameters=update_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _migrate_mongo_db_database_to_autoscale_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_mongo_db_database_to_autoscale_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_migrate_mongo_db_database_to_autoscale( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB MongoDB database from manual throughput to autoscale. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._migrate_mongo_db_database_to_autoscale_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _migrate_mongo_db_database_to_manual_throughput_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_mongo_db_database_to_manual_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_migrate_mongo_db_database_to_manual_throughput( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB MongoDB database from autoscale to manual throughput. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._migrate_mongo_db_database_to_manual_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _mongo_db_database_retrieve_throughput_distribution_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(retrieve_throughput_parameters, (IOBase, bytes)): + _content = retrieve_throughput_parameters + else: + _json = self._serialize.body(retrieve_throughput_parameters, "RetrieveThroughputParameters") + + _request = build_mongo_db_database_retrieve_throughput_distribution_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_mongo_db_database_retrieve_throughput_distribution( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + retrieve_throughput_parameters: _models.RetrieveThroughputParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Retrieve throughput distribution for an Azure Cosmos DB MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput + distribution for the current MongoDB database. Required. + :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_mongo_db_database_retrieve_throughput_distribution( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + retrieve_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Retrieve throughput distribution for an Azure Cosmos DB MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput + distribution for the current MongoDB database. Required. + :type retrieve_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_mongo_db_database_retrieve_throughput_distribution( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Retrieve throughput distribution for an Azure Cosmos DB MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput + distribution for the current MongoDB database. Is either a RetrieveThroughputParameters type or + a IO[bytes] type. Required. + :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters + or IO[bytes] + :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._mongo_db_database_retrieve_throughput_distribution_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + retrieve_throughput_parameters=retrieve_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.PhysicalPartitionThroughputInfoResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _mongo_db_database_redistribute_throughput_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(redistribute_throughput_parameters, (IOBase, bytes)): + _content = redistribute_throughput_parameters + else: + _json = self._serialize.body(redistribute_throughput_parameters, "RedistributeThroughputParameters") + + _request = build_mongo_db_database_redistribute_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_mongo_db_database_redistribute_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + redistribute_throughput_parameters: _models.RedistributeThroughputParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Redistribute throughput for an Azure Cosmos DB MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param redistribute_throughput_parameters: The parameters to provide for redistributing + throughput for the current MongoDB database. Required. + :type redistribute_throughput_parameters: + ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_mongo_db_database_redistribute_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + redistribute_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Redistribute throughput for an Azure Cosmos DB MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param redistribute_throughput_parameters: The parameters to provide for redistributing + throughput for the current MongoDB database. Required. + :type redistribute_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_mongo_db_database_redistribute_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Redistribute throughput for an Azure Cosmos DB MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param redistribute_throughput_parameters: The parameters to provide for redistributing + throughput for the current MongoDB database. Is either a RedistributeThroughputParameters type + or a IO[bytes] type. Required. + :type redistribute_throughput_parameters: + ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters or IO[bytes] + :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._mongo_db_database_redistribute_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + redistribute_throughput_parameters=redistribute_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.PhysicalPartitionThroughputInfoResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _mongo_db_container_retrieve_throughput_distribution_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(retrieve_throughput_parameters, (IOBase, bytes)): + _content = retrieve_throughput_parameters + else: + _json = self._serialize.body(retrieve_throughput_parameters, "RetrieveThroughputParameters") + + _request = build_mongo_db_container_retrieve_throughput_distribution_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_mongo_db_container_retrieve_throughput_distribution( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + retrieve_throughput_parameters: _models.RetrieveThroughputParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Retrieve throughput distribution for an Azure Cosmos DB MongoDB container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput + distribution for the current MongoDB container. Required. + :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_mongo_db_container_retrieve_throughput_distribution( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + retrieve_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Retrieve throughput distribution for an Azure Cosmos DB MongoDB container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput + distribution for the current MongoDB container. Required. + :type retrieve_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_mongo_db_container_retrieve_throughput_distribution( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Retrieve throughput distribution for an Azure Cosmos DB MongoDB container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput + distribution for the current MongoDB container. Is either a RetrieveThroughputParameters type + or a IO[bytes] type. Required. + :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters + or IO[bytes] + :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._mongo_db_container_retrieve_throughput_distribution_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + retrieve_throughput_parameters=retrieve_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.PhysicalPartitionThroughputInfoResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _mongo_db_container_redistribute_throughput_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(redistribute_throughput_parameters, (IOBase, bytes)): + _content = redistribute_throughput_parameters + else: + _json = self._serialize.body(redistribute_throughput_parameters, "RedistributeThroughputParameters") + + _request = build_mongo_db_container_redistribute_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_mongo_db_container_redistribute_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + redistribute_throughput_parameters: _models.RedistributeThroughputParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Redistribute throughput for an Azure Cosmos DB MongoDB container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param redistribute_throughput_parameters: The parameters to provide for redistributing + throughput for the current MongoDB container. Required. + :type redistribute_throughput_parameters: + ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_mongo_db_container_redistribute_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + redistribute_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Redistribute throughput for an Azure Cosmos DB MongoDB container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param redistribute_throughput_parameters: The parameters to provide for redistributing + throughput for the current MongoDB container. Required. + :type redistribute_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_mongo_db_container_redistribute_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Redistribute throughput for an Azure Cosmos DB MongoDB container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param redistribute_throughput_parameters: The parameters to provide for redistributing + throughput for the current MongoDB container. Is either a RedistributeThroughputParameters type + or a IO[bytes] type. Required. + :type redistribute_throughput_parameters: + ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters or IO[bytes] + :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._mongo_db_container_redistribute_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + redistribute_throughput_parameters=redistribute_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.PhysicalPartitionThroughputInfoResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def list_mongo_db_collections( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> Iterable["_models.MongoDBCollectionGetResults"]: + """Lists the MongoDB collection under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: An iterator like instance of either MongoDBCollectionGetResults or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.MongoDBCollectionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MongoDBCollectionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_mongo_db_collections_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("MongoDBCollectionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get_mongo_db_collection( + self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any + ) -> _models.MongoDBCollectionGetResults: + """Gets the MongoDB collection under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :return: MongoDBCollectionGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.MongoDBCollectionGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MongoDBCollectionGetResults] = kwargs.pop("cls", None) + + _request = build_get_mongo_db_collection_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("MongoDBCollectionGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_update_mongo_db_collection_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + create_update_mongo_db_collection_parameters: Union[_models.MongoDBCollectionCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_mongo_db_collection_parameters, (IOBase, bytes)): + _content = create_update_mongo_db_collection_parameters + else: + _json = self._serialize.body( + create_update_mongo_db_collection_parameters, "MongoDBCollectionCreateUpdateParameters" + ) + + _request = build_create_update_mongo_db_collection_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_update_mongo_db_collection( + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + create_update_mongo_db_collection_parameters: _models.MongoDBCollectionCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.MongoDBCollectionGetResults]: + """Create or update an Azure Cosmos DB MongoDB Collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param create_update_mongo_db_collection_parameters: The parameters to provide for the current + MongoDB Collection. Required. + :type create_update_mongo_db_collection_parameters: + ~azure.mgmt.cosmosdb.models.MongoDBCollectionCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either MongoDBCollectionGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.MongoDBCollectionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_update_mongo_db_collection( + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + create_update_mongo_db_collection_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.MongoDBCollectionGetResults]: + """Create or update an Azure Cosmos DB MongoDB Collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param create_update_mongo_db_collection_parameters: The parameters to provide for the current + MongoDB Collection. Required. + :type create_update_mongo_db_collection_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either MongoDBCollectionGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.MongoDBCollectionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_update_mongo_db_collection( + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + create_update_mongo_db_collection_parameters: Union[_models.MongoDBCollectionCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.MongoDBCollectionGetResults]: + """Create or update an Azure Cosmos DB MongoDB Collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param create_update_mongo_db_collection_parameters: The parameters to provide for the current + MongoDB Collection. Is either a MongoDBCollectionCreateUpdateParameters type or a IO[bytes] + type. Required. + :type create_update_mongo_db_collection_parameters: + ~azure.mgmt.cosmosdb.models.MongoDBCollectionCreateUpdateParameters or IO[bytes] + :return: An instance of LROPoller that returns either MongoDBCollectionGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.MongoDBCollectionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.MongoDBCollectionGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_update_mongo_db_collection_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + create_update_mongo_db_collection_parameters=create_update_mongo_db_collection_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("MongoDBCollectionGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.MongoDBCollectionGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.MongoDBCollectionGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_mongo_db_collection_initial( + self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_mongo_db_collection_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete_mongo_db_collection( + self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Deletes an existing Azure Cosmos DB MongoDB Collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_mongo_db_collection_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + def _mongo_db_database_partition_merge_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + merge_parameters: Union[_models.MergeParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(merge_parameters, (IOBase, bytes)): + _content = merge_parameters + else: + _json = self._serialize.body(merge_parameters, "MergeParameters") + + _request = build_mongo_db_database_partition_merge_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_mongo_db_database_partition_merge( + self, + resource_group_name: str, + account_name: str, + database_name: str, + merge_parameters: _models.MergeParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionStorageInfoCollection]: + """Merges the partitions of a MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param merge_parameters: The parameters for the merge operation. Required. + :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either PhysicalPartitionStorageInfoCollection or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_mongo_db_database_partition_merge( + self, + resource_group_name: str, + account_name: str, + database_name: str, + merge_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionStorageInfoCollection]: + """Merges the partitions of a MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param merge_parameters: The parameters for the merge operation. Required. + :type merge_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either PhysicalPartitionStorageInfoCollection or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_mongo_db_database_partition_merge( + self, + resource_group_name: str, + account_name: str, + database_name: str, + merge_parameters: Union[_models.MergeParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionStorageInfoCollection]: + """Merges the partitions of a MongoDB database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param merge_parameters: The parameters for the merge operation. Is either a MergeParameters + type or a IO[bytes] type. Required. + :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters or IO[bytes] + :return: An instance of LROPoller that returns either PhysicalPartitionStorageInfoCollection or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PhysicalPartitionStorageInfoCollection] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._mongo_db_database_partition_merge_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + merge_parameters=merge_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("PhysicalPartitionStorageInfoCollection", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.PhysicalPartitionStorageInfoCollection].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.PhysicalPartitionStorageInfoCollection]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _list_mongo_db_collection_partition_merge_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + merge_parameters: Union[_models.MergeParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(merge_parameters, (IOBase, bytes)): + _content = merge_parameters + else: + _json = self._serialize.body(merge_parameters, "MergeParameters") + + _request = build_list_mongo_db_collection_partition_merge_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_list_mongo_db_collection_partition_merge( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + merge_parameters: _models.MergeParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionStorageInfoCollection]: + """Merges the partitions of a MongoDB Collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param merge_parameters: The parameters for the merge operation. Required. + :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either PhysicalPartitionStorageInfoCollection or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_list_mongo_db_collection_partition_merge( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + merge_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionStorageInfoCollection]: + """Merges the partitions of a MongoDB Collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param merge_parameters: The parameters for the merge operation. Required. + :type merge_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either PhysicalPartitionStorageInfoCollection or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_list_mongo_db_collection_partition_merge( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + merge_parameters: Union[_models.MergeParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionStorageInfoCollection]: + """Merges the partitions of a MongoDB Collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param merge_parameters: The parameters for the merge operation. Is either a MergeParameters + type or a IO[bytes] type. Required. + :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters or IO[bytes] + :return: An instance of LROPoller that returns either PhysicalPartitionStorageInfoCollection or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PhysicalPartitionStorageInfoCollection] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._list_mongo_db_collection_partition_merge_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + merge_parameters=merge_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("PhysicalPartitionStorageInfoCollection", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.PhysicalPartitionStorageInfoCollection].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.PhysicalPartitionStorageInfoCollection]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def get_mongo_db_collection_throughput( + self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any + ) -> _models.ThroughputSettingsGetResults: + """Gets the RUs per second of the MongoDB collection under an existing Azure Cosmos DB database + account with the provided name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :return: ThroughputSettingsGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + + _request = build_get_mongo_db_collection_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _update_mongo_db_collection_throughput_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(update_throughput_parameters, (IOBase, bytes)): + _content = update_throughput_parameters + else: + _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") + + _request = build_update_mongo_db_collection_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_update_mongo_db_collection_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Update the RUs per second of an Azure Cosmos DB MongoDB collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current MongoDB collection. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update_mongo_db_collection_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + update_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Update the RUs per second of an Azure Cosmos DB MongoDB collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current MongoDB collection. Required. + :type update_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update_mongo_db_collection_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Update the RUs per second of an Azure Cosmos DB MongoDB collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param update_throughput_parameters: The RUs per second of the parameters to provide for the + current MongoDB collection. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] + type. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._update_mongo_db_collection_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + update_throughput_parameters=update_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _migrate_mongo_db_collection_to_autoscale_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_mongo_db_collection_to_autoscale_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_migrate_mongo_db_collection_to_autoscale( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB MongoDB collection from manual throughput to autoscale. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._migrate_mongo_db_collection_to_autoscale_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _migrate_mongo_db_collection_to_manual_throughput_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_mongo_db_collection_to_manual_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_migrate_mongo_db_collection_to_manual_throughput( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB MongoDB collection from autoscale to manual throughput. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._migrate_mongo_db_collection_to_manual_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def get_mongo_role_definition( + self, mongo_role_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any + ) -> _models.MongoRoleDefinitionGetResults: + """Retrieves the properties of an existing Azure Cosmos DB Mongo Role Definition with the given + Id. + + :param mongo_role_definition_id: The ID for the Role Definition {dbName.roleName}. Required. + :type mongo_role_definition_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: MongoRoleDefinitionGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.MongoRoleDefinitionGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MongoRoleDefinitionGetResults] = kwargs.pop("cls", None) + + _request = build_get_mongo_role_definition_request( + mongo_role_definition_id=mongo_role_definition_id, + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("MongoRoleDefinitionGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_update_mongo_role_definition_initial( # pylint: disable=name-too-long + self, + mongo_role_definition_id: str, + resource_group_name: str, + account_name: str, + create_update_mongo_role_definition_parameters: Union[ + _models.MongoRoleDefinitionCreateUpdateParameters, IO[bytes] + ], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_mongo_role_definition_parameters, (IOBase, bytes)): + _content = create_update_mongo_role_definition_parameters + else: + _json = self._serialize.body( + create_update_mongo_role_definition_parameters, "MongoRoleDefinitionCreateUpdateParameters" + ) + + _request = build_create_update_mongo_role_definition_request( + mongo_role_definition_id=mongo_role_definition_id, + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_update_mongo_role_definition( # pylint: disable=name-too-long + self, + mongo_role_definition_id: str, + resource_group_name: str, + account_name: str, + create_update_mongo_role_definition_parameters: _models.MongoRoleDefinitionCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.MongoRoleDefinitionGetResults]: + """Creates or updates an Azure Cosmos DB Mongo Role Definition. + + :param mongo_role_definition_id: The ID for the Role Definition {dbName.roleName}. Required. + :type mongo_role_definition_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param create_update_mongo_role_definition_parameters: The properties required to create or + update a Role Definition. Required. + :type create_update_mongo_role_definition_parameters: + ~azure.mgmt.cosmosdb.models.MongoRoleDefinitionCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either MongoRoleDefinitionGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.MongoRoleDefinitionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_update_mongo_role_definition( # pylint: disable=name-too-long + self, + mongo_role_definition_id: str, + resource_group_name: str, + account_name: str, + create_update_mongo_role_definition_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.MongoRoleDefinitionGetResults]: + """Creates or updates an Azure Cosmos DB Mongo Role Definition. + + :param mongo_role_definition_id: The ID for the Role Definition {dbName.roleName}. Required. + :type mongo_role_definition_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param create_update_mongo_role_definition_parameters: The properties required to create or + update a Role Definition. Required. + :type create_update_mongo_role_definition_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either MongoRoleDefinitionGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.MongoRoleDefinitionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_update_mongo_role_definition( # pylint: disable=name-too-long + self, + mongo_role_definition_id: str, + resource_group_name: str, + account_name: str, + create_update_mongo_role_definition_parameters: Union[ + _models.MongoRoleDefinitionCreateUpdateParameters, IO[bytes] + ], + **kwargs: Any + ) -> LROPoller[_models.MongoRoleDefinitionGetResults]: + """Creates or updates an Azure Cosmos DB Mongo Role Definition. + + :param mongo_role_definition_id: The ID for the Role Definition {dbName.roleName}. Required. + :type mongo_role_definition_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param create_update_mongo_role_definition_parameters: The properties required to create or + update a Role Definition. Is either a MongoRoleDefinitionCreateUpdateParameters type or a + IO[bytes] type. Required. + :type create_update_mongo_role_definition_parameters: + ~azure.mgmt.cosmosdb.models.MongoRoleDefinitionCreateUpdateParameters or IO[bytes] + :return: An instance of LROPoller that returns either MongoRoleDefinitionGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.MongoRoleDefinitionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.MongoRoleDefinitionGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_update_mongo_role_definition_initial( + mongo_role_definition_id=mongo_role_definition_id, + resource_group_name=resource_group_name, + account_name=account_name, + create_update_mongo_role_definition_parameters=create_update_mongo_role_definition_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("MongoRoleDefinitionGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.MongoRoleDefinitionGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.MongoRoleDefinitionGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_mongo_role_definition_initial( + self, mongo_role_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_mongo_role_definition_request( + mongo_role_definition_id=mongo_role_definition_id, + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete_mongo_role_definition( + self, mongo_role_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Deletes an existing Azure Cosmos DB Mongo Role Definition. + + :param mongo_role_definition_id: The ID for the Role Definition {dbName.roleName}. Required. + :type mongo_role_definition_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_mongo_role_definition_initial( + mongo_role_definition_id=mongo_role_definition_id, + resource_group_name=resource_group_name, + account_name=account_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def list_mongo_role_definitions( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> Iterable["_models.MongoRoleDefinitionGetResults"]: + """Retrieves the list of all Azure Cosmos DB Mongo Role Definitions. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either MongoRoleDefinitionGetResults or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.MongoRoleDefinitionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MongoRoleDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_mongo_role_definitions_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("MongoRoleDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get_mongo_user_definition( + self, mongo_user_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any + ) -> _models.MongoUserDefinitionGetResults: + """Retrieves the properties of an existing Azure Cosmos DB Mongo User Definition with the given + Id. + + :param mongo_user_definition_id: The ID for the User Definition {dbName.userName}. Required. + :type mongo_user_definition_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: MongoUserDefinitionGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.MongoUserDefinitionGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MongoUserDefinitionGetResults] = kwargs.pop("cls", None) + + _request = build_get_mongo_user_definition_request( + mongo_user_definition_id=mongo_user_definition_id, + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("MongoUserDefinitionGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_update_mongo_user_definition_initial( # pylint: disable=name-too-long + self, + mongo_user_definition_id: str, + resource_group_name: str, + account_name: str, + create_update_mongo_user_definition_parameters: Union[ + _models.MongoUserDefinitionCreateUpdateParameters, IO[bytes] + ], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_mongo_user_definition_parameters, (IOBase, bytes)): + _content = create_update_mongo_user_definition_parameters + else: + _json = self._serialize.body( + create_update_mongo_user_definition_parameters, "MongoUserDefinitionCreateUpdateParameters" + ) + + _request = build_create_update_mongo_user_definition_request( + mongo_user_definition_id=mongo_user_definition_id, + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_update_mongo_user_definition( # pylint: disable=name-too-long + self, + mongo_user_definition_id: str, + resource_group_name: str, + account_name: str, + create_update_mongo_user_definition_parameters: _models.MongoUserDefinitionCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.MongoUserDefinitionGetResults]: + """Creates or updates an Azure Cosmos DB Mongo User Definition. + + :param mongo_user_definition_id: The ID for the User Definition {dbName.userName}. Required. + :type mongo_user_definition_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param create_update_mongo_user_definition_parameters: The properties required to create or + update a User Definition. Required. + :type create_update_mongo_user_definition_parameters: + ~azure.mgmt.cosmosdb.models.MongoUserDefinitionCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either MongoUserDefinitionGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.MongoUserDefinitionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_update_mongo_user_definition( # pylint: disable=name-too-long + self, + mongo_user_definition_id: str, + resource_group_name: str, + account_name: str, + create_update_mongo_user_definition_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.MongoUserDefinitionGetResults]: + """Creates or updates an Azure Cosmos DB Mongo User Definition. + + :param mongo_user_definition_id: The ID for the User Definition {dbName.userName}. Required. + :type mongo_user_definition_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param create_update_mongo_user_definition_parameters: The properties required to create or + update a User Definition. Required. + :type create_update_mongo_user_definition_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either MongoUserDefinitionGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.MongoUserDefinitionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_update_mongo_user_definition( # pylint: disable=name-too-long + self, + mongo_user_definition_id: str, + resource_group_name: str, + account_name: str, + create_update_mongo_user_definition_parameters: Union[ + _models.MongoUserDefinitionCreateUpdateParameters, IO[bytes] + ], + **kwargs: Any + ) -> LROPoller[_models.MongoUserDefinitionGetResults]: + """Creates or updates an Azure Cosmos DB Mongo User Definition. + + :param mongo_user_definition_id: The ID for the User Definition {dbName.userName}. Required. + :type mongo_user_definition_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param create_update_mongo_user_definition_parameters: The properties required to create or + update a User Definition. Is either a MongoUserDefinitionCreateUpdateParameters type or a + IO[bytes] type. Required. + :type create_update_mongo_user_definition_parameters: + ~azure.mgmt.cosmosdb.models.MongoUserDefinitionCreateUpdateParameters or IO[bytes] + :return: An instance of LROPoller that returns either MongoUserDefinitionGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.MongoUserDefinitionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.MongoUserDefinitionGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_update_mongo_user_definition_initial( + mongo_user_definition_id=mongo_user_definition_id, + resource_group_name=resource_group_name, + account_name=account_name, + create_update_mongo_user_definition_parameters=create_update_mongo_user_definition_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("MongoUserDefinitionGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.MongoUserDefinitionGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.MongoUserDefinitionGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_mongo_user_definition_initial( + self, mongo_user_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_mongo_user_definition_request( + mongo_user_definition_id=mongo_user_definition_id, + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete_mongo_user_definition( + self, mongo_user_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Deletes an existing Azure Cosmos DB Mongo User Definition. + + :param mongo_user_definition_id: The ID for the User Definition {dbName.userName}. Required. + :type mongo_user_definition_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_mongo_user_definition_initial( + mongo_user_definition_id=mongo_user_definition_id, + resource_group_name=resource_group_name, + account_name=account_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def list_mongo_user_definitions( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> Iterable["_models.MongoUserDefinitionGetResults"]: + """Retrieves the list of all Azure Cosmos DB Mongo User Definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either MongoUserDefinitionGetResults or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.MongoUserDefinitionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MongoUserDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_mongo_user_definitions_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("MongoUserDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + def _retrieve_continuous_backup_information_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(location, (IOBase, bytes)): + _content = location + else: + _json = self._serialize.body(location, "ContinuousBackupRestoreLocation") + + _request = build_retrieve_continuous_backup_information_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + location: _models.ContinuousBackupRestoreLocation, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.BackupInformation]: + """Retrieves continuous backup information for a Mongodb collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param location: The name of the continuous backup restore location. Required. + :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either BackupInformation or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + location: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.BackupInformation]: + """Retrieves continuous backup information for a Mongodb collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param location: The name of the continuous backup restore location. Required. + :type location: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either BackupInformation or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + collection_name: str, + location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.BackupInformation]: + """Retrieves continuous backup information for a Mongodb collection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param collection_name: Cosmos DB collection name. Required. + :type collection_name: str + :param location: The name of the continuous backup restore location. Is either a + ContinuousBackupRestoreLocation type or a IO[bytes] type. Required. + :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation or IO[bytes] + :return: An instance of LROPoller that returns either BackupInformation or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.BackupInformation] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._retrieve_continuous_backup_information_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + collection_name=collection_name, + location=location, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("BackupInformation", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.BackupInformation].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.BackupInformation]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_network_security_perimeter_configurations_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_network_security_perimeter_configurations_operations.py index f3cdcd9df58..78b765b4bf6 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_network_security_perimeter_configurations_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_network_security_perimeter_configurations_operations.py @@ -1,462 +1,462 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Iterator, Optional, Type, TypeVar, Union, cast -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.arm_polling import ARMPolling - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_request(resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/networkSecurityPerimeterConfigurations", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request( - resource_group_name: str, - account_name: str, - network_security_perimeter_configuration_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/networkSecurityPerimeterConfigurations/{networkSecurityPerimeterConfigurationName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "networkSecurityPerimeterConfigurationName": _SERIALIZER.url( - "network_security_perimeter_configuration_name", - network_security_perimeter_configuration_name, - "str", - pattern=r"^.*$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_reconcile_request( - resource_group_name: str, - account_name: str, - network_security_perimeter_configuration_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/networkSecurityPerimeterConfigurations/{networkSecurityPerimeterConfigurationName}/reconcile", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "networkSecurityPerimeterConfigurationName": _SERIALIZER.url( - "network_security_perimeter_configuration_name", - network_security_perimeter_configuration_name, - "str", - pattern=r"^.*$", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -class NetworkSecurityPerimeterConfigurationsOperations: # pylint: disable=name-too-long - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`network_security_perimeter_configurations` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> Iterable["_models.NetworkSecurityPerimeterConfiguration"]: - """Gets list of effective Network Security Perimeter Configuration for cosmos db account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either NetworkSecurityPerimeterConfiguration or the - result of cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.NetworkSecurityPerimeterConfiguration] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.NetworkSecurityPerimeterConfigurationListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("NetworkSecurityPerimeterConfigurationListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get( - self, - resource_group_name: str, - account_name: str, - network_security_perimeter_configuration_name: str, - **kwargs: Any - ) -> _models.NetworkSecurityPerimeterConfiguration: - """Gets effective Network Security Perimeter Configuration for association. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param network_security_perimeter_configuration_name: The name for Network Security Perimeter - configuration. Required. - :type network_security_perimeter_configuration_name: str - :return: NetworkSecurityPerimeterConfiguration or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.NetworkSecurityPerimeterConfiguration - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.NetworkSecurityPerimeterConfiguration] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - account_name=account_name, - network_security_perimeter_configuration_name=network_security_perimeter_configuration_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("NetworkSecurityPerimeterConfiguration", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _reconcile_initial( - self, - resource_group_name: str, - account_name: str, - network_security_perimeter_configuration_name: str, - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_reconcile_request( - resource_group_name=resource_group_name, - account_name=account_name, - network_security_perimeter_configuration_name=network_security_perimeter_configuration_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_reconcile( - self, - resource_group_name: str, - account_name: str, - network_security_perimeter_configuration_name: str, - **kwargs: Any - ) -> LROPoller[None]: - """Refreshes any information about the association. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param network_security_perimeter_configuration_name: The name for Network Security Perimeter - configuration. Required. - :type network_security_perimeter_configuration_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._reconcile_initial( - resource_group_name=resource_group_name, - account_name=account_name, - network_security_perimeter_configuration_name=network_security_perimeter_configuration_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Iterator, Optional, Type, TypeVar, Union, cast +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/networkSecurityPerimeterConfigurations", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request( + resource_group_name: str, + account_name: str, + network_security_perimeter_configuration_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/networkSecurityPerimeterConfigurations/{networkSecurityPerimeterConfigurationName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "networkSecurityPerimeterConfigurationName": _SERIALIZER.url( + "network_security_perimeter_configuration_name", + network_security_perimeter_configuration_name, + "str", + pattern=r"^.*$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_reconcile_request( + resource_group_name: str, + account_name: str, + network_security_perimeter_configuration_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/networkSecurityPerimeterConfigurations/{networkSecurityPerimeterConfigurationName}/reconcile", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "networkSecurityPerimeterConfigurationName": _SERIALIZER.url( + "network_security_perimeter_configuration_name", + network_security_perimeter_configuration_name, + "str", + pattern=r"^.*$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class NetworkSecurityPerimeterConfigurationsOperations: # pylint: disable=name-too-long + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`network_security_perimeter_configurations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> Iterable["_models.NetworkSecurityPerimeterConfiguration"]: + """Gets list of effective Network Security Perimeter Configuration for cosmos db account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either NetworkSecurityPerimeterConfiguration or the + result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.NetworkSecurityPerimeterConfiguration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.NetworkSecurityPerimeterConfigurationListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("NetworkSecurityPerimeterConfigurationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get( + self, + resource_group_name: str, + account_name: str, + network_security_perimeter_configuration_name: str, + **kwargs: Any + ) -> _models.NetworkSecurityPerimeterConfiguration: + """Gets effective Network Security Perimeter Configuration for association. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param network_security_perimeter_configuration_name: The name for Network Security Perimeter + configuration. Required. + :type network_security_perimeter_configuration_name: str + :return: NetworkSecurityPerimeterConfiguration or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.NetworkSecurityPerimeterConfiguration + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.NetworkSecurityPerimeterConfiguration] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + account_name=account_name, + network_security_perimeter_configuration_name=network_security_perimeter_configuration_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("NetworkSecurityPerimeterConfiguration", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _reconcile_initial( + self, + resource_group_name: str, + account_name: str, + network_security_perimeter_configuration_name: str, + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_reconcile_request( + resource_group_name=resource_group_name, + account_name=account_name, + network_security_perimeter_configuration_name=network_security_perimeter_configuration_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_reconcile( + self, + resource_group_name: str, + account_name: str, + network_security_perimeter_configuration_name: str, + **kwargs: Any + ) -> LROPoller[None]: + """Refreshes any information about the association. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param network_security_perimeter_configuration_name: The name for Network Security Perimeter + configuration. Required. + :type network_security_perimeter_configuration_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._reconcile_initial( + resource_group_name=resource_group_name, + account_name=account_name, + network_security_perimeter_configuration_name=network_security_perimeter_configuration_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_notebook_workspaces_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_notebook_workspaces_operations.py index 5376274c08b..10c2ccba4dc 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_notebook_workspaces_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_notebook_workspaces_operations.py @@ -1,1128 +1,1128 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.arm_polling import ARMPolling - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_by_database_account_request( - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/notebookWorkspaces", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request( - resource_group_name: str, - account_name: str, - notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/notebookWorkspaces/{notebookWorkspaceName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "notebookWorkspaceName": _SERIALIZER.url("notebook_workspace_name", notebook_workspace_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_or_update_request( - resource_group_name: str, - account_name: str, - notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/notebookWorkspaces/{notebookWorkspaceName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "notebookWorkspaceName": _SERIALIZER.url("notebook_workspace_name", notebook_workspace_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - resource_group_name: str, - account_name: str, - notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/notebookWorkspaces/{notebookWorkspaceName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "notebookWorkspaceName": _SERIALIZER.url("notebook_workspace_name", notebook_workspace_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_connection_info_request( - resource_group_name: str, - account_name: str, - notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/notebookWorkspaces/{notebookWorkspaceName}/listConnectionInfo", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "notebookWorkspaceName": _SERIALIZER.url("notebook_workspace_name", notebook_workspace_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_regenerate_auth_token_request( - resource_group_name: str, - account_name: str, - notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/notebookWorkspaces/{notebookWorkspaceName}/regenerateAuthToken", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "notebookWorkspaceName": _SERIALIZER.url("notebook_workspace_name", notebook_workspace_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_start_request( - resource_group_name: str, - account_name: str, - notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/notebookWorkspaces/{notebookWorkspaceName}/start", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "notebookWorkspaceName": _SERIALIZER.url("notebook_workspace_name", notebook_workspace_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -class NotebookWorkspacesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`notebook_workspaces` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_by_database_account( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> Iterable["_models.NotebookWorkspace"]: - """Gets the notebook workspace resources of an existing Cosmos DB account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either NotebookWorkspace or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.NotebookWorkspace] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.NotebookWorkspaceListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_by_database_account_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("NotebookWorkspaceListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get( - self, - resource_group_name: str, - account_name: str, - notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], - **kwargs: Any - ) -> _models.NotebookWorkspace: - """Gets the notebook workspace for a Cosmos DB account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param notebook_workspace_name: The name of the notebook workspace resource. "default" - Required. - :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName - :return: NotebookWorkspace or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.NotebookWorkspace - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.NotebookWorkspace] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - account_name=account_name, - notebook_workspace_name=notebook_workspace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("NotebookWorkspace", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _create_or_update_initial( - self, - resource_group_name: str, - account_name: str, - notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], - notebook_create_update_parameters: Union[_models.NotebookWorkspaceCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(notebook_create_update_parameters, (IOBase, bytes)): - _content = notebook_create_update_parameters - else: - _json = self._serialize.body(notebook_create_update_parameters, "NotebookWorkspaceCreateUpdateParameters") - - _request = build_create_or_update_request( - resource_group_name=resource_group_name, - account_name=account_name, - notebook_workspace_name=notebook_workspace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_or_update( - self, - resource_group_name: str, - account_name: str, - notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], - notebook_create_update_parameters: _models.NotebookWorkspaceCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.NotebookWorkspace]: - """Creates the notebook workspace for a Cosmos DB account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param notebook_workspace_name: The name of the notebook workspace resource. "default" - Required. - :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName - :param notebook_create_update_parameters: The notebook workspace to create for the current - database account. Required. - :type notebook_create_update_parameters: - ~azure.mgmt.cosmosdb.models.NotebookWorkspaceCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either NotebookWorkspace or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.NotebookWorkspace] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_or_update( - self, - resource_group_name: str, - account_name: str, - notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], - notebook_create_update_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.NotebookWorkspace]: - """Creates the notebook workspace for a Cosmos DB account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param notebook_workspace_name: The name of the notebook workspace resource. "default" - Required. - :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName - :param notebook_create_update_parameters: The notebook workspace to create for the current - database account. Required. - :type notebook_create_update_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either NotebookWorkspace or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.NotebookWorkspace] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_or_update( - self, - resource_group_name: str, - account_name: str, - notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], - notebook_create_update_parameters: Union[_models.NotebookWorkspaceCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.NotebookWorkspace]: - """Creates the notebook workspace for a Cosmos DB account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param notebook_workspace_name: The name of the notebook workspace resource. "default" - Required. - :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName - :param notebook_create_update_parameters: The notebook workspace to create for the current - database account. Is either a NotebookWorkspaceCreateUpdateParameters type or a IO[bytes] type. - Required. - :type notebook_create_update_parameters: - ~azure.mgmt.cosmosdb.models.NotebookWorkspaceCreateUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either NotebookWorkspace or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.NotebookWorkspace] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.NotebookWorkspace] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_or_update_initial( - resource_group_name=resource_group_name, - account_name=account_name, - notebook_workspace_name=notebook_workspace_name, - notebook_create_update_parameters=notebook_create_update_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("NotebookWorkspace", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.NotebookWorkspace].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.NotebookWorkspace]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _delete_initial( - self, - resource_group_name: str, - account_name: str, - notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - account_name=account_name, - notebook_workspace_name=notebook_workspace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete( - self, - resource_group_name: str, - account_name: str, - notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], - **kwargs: Any - ) -> LROPoller[None]: - """Deletes the notebook workspace for a Cosmos DB account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param notebook_workspace_name: The name of the notebook workspace resource. "default" - Required. - :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_initial( - resource_group_name=resource_group_name, - account_name=account_name, - notebook_workspace_name=notebook_workspace_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace - def list_connection_info( - self, - resource_group_name: str, - account_name: str, - notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], - **kwargs: Any - ) -> _models.NotebookWorkspaceConnectionInfoResult: - """Retrieves the connection info for the notebook workspace. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param notebook_workspace_name: The name of the notebook workspace resource. "default" - Required. - :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName - :return: NotebookWorkspaceConnectionInfoResult or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.NotebookWorkspaceConnectionInfoResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.NotebookWorkspaceConnectionInfoResult] = kwargs.pop("cls", None) - - _request = build_list_connection_info_request( - resource_group_name=resource_group_name, - account_name=account_name, - notebook_workspace_name=notebook_workspace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("NotebookWorkspaceConnectionInfoResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _regenerate_auth_token_initial( - self, - resource_group_name: str, - account_name: str, - notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_regenerate_auth_token_request( - resource_group_name=resource_group_name, - account_name=account_name, - notebook_workspace_name=notebook_workspace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_regenerate_auth_token( - self, - resource_group_name: str, - account_name: str, - notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], - **kwargs: Any - ) -> LROPoller[None]: - """Regenerates the auth token for the notebook workspace. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param notebook_workspace_name: The name of the notebook workspace resource. "default" - Required. - :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._regenerate_auth_token_initial( - resource_group_name=resource_group_name, - account_name=account_name, - notebook_workspace_name=notebook_workspace_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - def _start_initial( - self, - resource_group_name: str, - account_name: str, - notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_start_request( - resource_group_name=resource_group_name, - account_name=account_name, - notebook_workspace_name=notebook_workspace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_start( - self, - resource_group_name: str, - account_name: str, - notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], - **kwargs: Any - ) -> LROPoller[None]: - """Starts the notebook workspace. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param notebook_workspace_name: The name of the notebook workspace resource. "default" - Required. - :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._start_initial( - resource_group_name=resource_group_name, - account_name=account_name, - notebook_workspace_name=notebook_workspace_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_by_database_account_request( + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/notebookWorkspaces", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request( + resource_group_name: str, + account_name: str, + notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/notebookWorkspaces/{notebookWorkspaceName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "notebookWorkspaceName": _SERIALIZER.url("notebook_workspace_name", notebook_workspace_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request( + resource_group_name: str, + account_name: str, + notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/notebookWorkspaces/{notebookWorkspaceName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "notebookWorkspaceName": _SERIALIZER.url("notebook_workspace_name", notebook_workspace_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, + account_name: str, + notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/notebookWorkspaces/{notebookWorkspaceName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "notebookWorkspaceName": _SERIALIZER.url("notebook_workspace_name", notebook_workspace_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_connection_info_request( + resource_group_name: str, + account_name: str, + notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/notebookWorkspaces/{notebookWorkspaceName}/listConnectionInfo", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "notebookWorkspaceName": _SERIALIZER.url("notebook_workspace_name", notebook_workspace_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_regenerate_auth_token_request( + resource_group_name: str, + account_name: str, + notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/notebookWorkspaces/{notebookWorkspaceName}/regenerateAuthToken", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "notebookWorkspaceName": _SERIALIZER.url("notebook_workspace_name", notebook_workspace_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_start_request( + resource_group_name: str, + account_name: str, + notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/notebookWorkspaces/{notebookWorkspaceName}/start", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "notebookWorkspaceName": _SERIALIZER.url("notebook_workspace_name", notebook_workspace_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class NotebookWorkspacesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`notebook_workspaces` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_by_database_account( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> Iterable["_models.NotebookWorkspace"]: + """Gets the notebook workspace resources of an existing Cosmos DB account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either NotebookWorkspace or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.NotebookWorkspace] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.NotebookWorkspaceListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_database_account_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("NotebookWorkspaceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get( + self, + resource_group_name: str, + account_name: str, + notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], + **kwargs: Any + ) -> _models.NotebookWorkspace: + """Gets the notebook workspace for a Cosmos DB account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param notebook_workspace_name: The name of the notebook workspace resource. "default" + Required. + :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName + :return: NotebookWorkspace or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.NotebookWorkspace + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.NotebookWorkspace] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + account_name=account_name, + notebook_workspace_name=notebook_workspace_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("NotebookWorkspace", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_or_update_initial( + self, + resource_group_name: str, + account_name: str, + notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], + notebook_create_update_parameters: Union[_models.NotebookWorkspaceCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(notebook_create_update_parameters, (IOBase, bytes)): + _content = notebook_create_update_parameters + else: + _json = self._serialize.body(notebook_create_update_parameters, "NotebookWorkspaceCreateUpdateParameters") + + _request = build_create_or_update_request( + resource_group_name=resource_group_name, + account_name=account_name, + notebook_workspace_name=notebook_workspace_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + account_name: str, + notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], + notebook_create_update_parameters: _models.NotebookWorkspaceCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.NotebookWorkspace]: + """Creates the notebook workspace for a Cosmos DB account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param notebook_workspace_name: The name of the notebook workspace resource. "default" + Required. + :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName + :param notebook_create_update_parameters: The notebook workspace to create for the current + database account. Required. + :type notebook_create_update_parameters: + ~azure.mgmt.cosmosdb.models.NotebookWorkspaceCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either NotebookWorkspace or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.NotebookWorkspace] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + account_name: str, + notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], + notebook_create_update_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.NotebookWorkspace]: + """Creates the notebook workspace for a Cosmos DB account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param notebook_workspace_name: The name of the notebook workspace resource. "default" + Required. + :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName + :param notebook_create_update_parameters: The notebook workspace to create for the current + database account. Required. + :type notebook_create_update_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either NotebookWorkspace or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.NotebookWorkspace] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + account_name: str, + notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], + notebook_create_update_parameters: Union[_models.NotebookWorkspaceCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.NotebookWorkspace]: + """Creates the notebook workspace for a Cosmos DB account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param notebook_workspace_name: The name of the notebook workspace resource. "default" + Required. + :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName + :param notebook_create_update_parameters: The notebook workspace to create for the current + database account. Is either a NotebookWorkspaceCreateUpdateParameters type or a IO[bytes] type. + Required. + :type notebook_create_update_parameters: + ~azure.mgmt.cosmosdb.models.NotebookWorkspaceCreateUpdateParameters or IO[bytes] + :return: An instance of LROPoller that returns either NotebookWorkspace or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.NotebookWorkspace] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.NotebookWorkspace] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + account_name=account_name, + notebook_workspace_name=notebook_workspace_name, + notebook_create_update_parameters=notebook_create_update_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("NotebookWorkspace", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.NotebookWorkspace].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.NotebookWorkspace]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_initial( + self, + resource_group_name: str, + account_name: str, + notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + account_name=account_name, + notebook_workspace_name=notebook_workspace_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete( + self, + resource_group_name: str, + account_name: str, + notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], + **kwargs: Any + ) -> LROPoller[None]: + """Deletes the notebook workspace for a Cosmos DB account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param notebook_workspace_name: The name of the notebook workspace resource. "default" + Required. + :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + account_name=account_name, + notebook_workspace_name=notebook_workspace_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def list_connection_info( + self, + resource_group_name: str, + account_name: str, + notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], + **kwargs: Any + ) -> _models.NotebookWorkspaceConnectionInfoResult: + """Retrieves the connection info for the notebook workspace. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param notebook_workspace_name: The name of the notebook workspace resource. "default" + Required. + :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName + :return: NotebookWorkspaceConnectionInfoResult or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.NotebookWorkspaceConnectionInfoResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.NotebookWorkspaceConnectionInfoResult] = kwargs.pop("cls", None) + + _request = build_list_connection_info_request( + resource_group_name=resource_group_name, + account_name=account_name, + notebook_workspace_name=notebook_workspace_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("NotebookWorkspaceConnectionInfoResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _regenerate_auth_token_initial( + self, + resource_group_name: str, + account_name: str, + notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_regenerate_auth_token_request( + resource_group_name=resource_group_name, + account_name=account_name, + notebook_workspace_name=notebook_workspace_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_regenerate_auth_token( + self, + resource_group_name: str, + account_name: str, + notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], + **kwargs: Any + ) -> LROPoller[None]: + """Regenerates the auth token for the notebook workspace. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param notebook_workspace_name: The name of the notebook workspace resource. "default" + Required. + :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._regenerate_auth_token_initial( + resource_group_name=resource_group_name, + account_name=account_name, + notebook_workspace_name=notebook_workspace_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + def _start_initial( + self, + resource_group_name: str, + account_name: str, + notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_start_request( + resource_group_name=resource_group_name, + account_name=account_name, + notebook_workspace_name=notebook_workspace_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_start( + self, + resource_group_name: str, + account_name: str, + notebook_workspace_name: Union[str, _models.NotebookWorkspaceName], + **kwargs: Any + ) -> LROPoller[None]: + """Starts the notebook workspace. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param notebook_workspace_name: The name of the notebook workspace resource. "default" + Required. + :type notebook_workspace_name: str or ~azure.mgmt.cosmosdb.models.NotebookWorkspaceName + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._start_initial( + resource_group_name=resource_group_name, + account_name=account_name, + notebook_workspace_name=notebook_workspace_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_operations.py index cf110a93545..646477151c1 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_operations.py @@ -1,151 +1,151 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_request(**kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.DocumentDB/operations") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class Operations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`operations` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: - """Lists all of the available Cosmos DB Resource Provider operations. - - :return: An iterator like instance of either Operation or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.Operation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("OperationListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.DocumentDB/operations") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`operations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: + """Lists all of the available Cosmos DB Resource Provider operations. + + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_partition_key_range_id_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_partition_key_range_id_operations.py index 6d04300053f..af5a44d645e 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_partition_key_range_id_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_partition_key_range_id_operations.py @@ -1,210 +1,210 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_metrics_request( - resource_group_name: str, - account_name: str, - database_rid: str, - collection_rid: str, - partition_key_range_id: str, - subscription_id: str, - *, - filter: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/databases/{databaseRid}/collections/{collectionRid}/partitionKeyRangeId/{partitionKeyRangeId}/metrics", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseRid": _SERIALIZER.url("database_rid", database_rid, "str"), - "collectionRid": _SERIALIZER.url("collection_rid", collection_rid, "str"), - "partitionKeyRangeId": _SERIALIZER.url("partition_key_range_id", partition_key_range_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class PartitionKeyRangeIdOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`partition_key_range_id` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_metrics( - self, - resource_group_name: str, - account_name: str, - database_rid: str, - collection_rid: str, - partition_key_range_id: str, - filter: str, - **kwargs: Any - ) -> Iterable["_models.PartitionMetric"]: - """Retrieves the metrics determined by the given filter for the given partition key range id. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_rid: Cosmos DB database rid. Required. - :type database_rid: str - :param collection_rid: Cosmos DB collection rid. Required. - :type collection_rid: str - :param partition_key_range_id: Partition Key Range Id for which to get data. Required. - :type partition_key_range_id: str - :param filter: An OData filter expression that describes a subset of metrics to return. The - parameters that can be filtered are name.value (name of the metric, can have an or of multiple - names), startTime, endTime, and timeGrain. The supported operator is eq. Required. - :type filter: str - :return: An iterator like instance of either PartitionMetric or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.PartitionMetric] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.PartitionMetricListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_metrics_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_rid=database_rid, - collection_rid=collection_rid, - partition_key_range_id=partition_key_range_id, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PartitionMetricListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_metrics_request( + resource_group_name: str, + account_name: str, + database_rid: str, + collection_rid: str, + partition_key_range_id: str, + subscription_id: str, + *, + filter: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/databases/{databaseRid}/collections/{collectionRid}/partitionKeyRangeId/{partitionKeyRangeId}/metrics", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseRid": _SERIALIZER.url("database_rid", database_rid, "str"), + "collectionRid": _SERIALIZER.url("collection_rid", collection_rid, "str"), + "partitionKeyRangeId": _SERIALIZER.url("partition_key_range_id", partition_key_range_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class PartitionKeyRangeIdOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`partition_key_range_id` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_metrics( + self, + resource_group_name: str, + account_name: str, + database_rid: str, + collection_rid: str, + partition_key_range_id: str, + filter: str, + **kwargs: Any + ) -> Iterable["_models.PartitionMetric"]: + """Retrieves the metrics determined by the given filter for the given partition key range id. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_rid: Cosmos DB database rid. Required. + :type database_rid: str + :param collection_rid: Cosmos DB collection rid. Required. + :type collection_rid: str + :param partition_key_range_id: Partition Key Range Id for which to get data. Required. + :type partition_key_range_id: str + :param filter: An OData filter expression that describes a subset of metrics to return. The + parameters that can be filtered are name.value (name of the metric, can have an or of multiple + names), startTime, endTime, and timeGrain. The supported operator is eq. Required. + :type filter: str + :return: An iterator like instance of either PartitionMetric or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.PartitionMetric] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PartitionMetricListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_metrics_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_rid=database_rid, + collection_rid=collection_rid, + partition_key_range_id=partition_key_range_id, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PartitionMetricListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_partition_key_range_id_region_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_partition_key_range_id_region_operations.py index 7a999ec7a44..8d7f9943b2c 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_partition_key_range_id_region_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_partition_key_range_id_region_operations.py @@ -1,217 +1,217 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_metrics_request( - resource_group_name: str, - account_name: str, - region: str, - database_rid: str, - collection_rid: str, - partition_key_range_id: str, - subscription_id: str, - *, - filter: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/region/{region}/databases/{databaseRid}/collections/{collectionRid}/partitionKeyRangeId/{partitionKeyRangeId}/metrics", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "region": _SERIALIZER.url("region", region, "str"), - "databaseRid": _SERIALIZER.url("database_rid", database_rid, "str"), - "collectionRid": _SERIALIZER.url("collection_rid", collection_rid, "str"), - "partitionKeyRangeId": _SERIALIZER.url("partition_key_range_id", partition_key_range_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class PartitionKeyRangeIdRegionOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`partition_key_range_id_region` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_metrics( - self, - resource_group_name: str, - account_name: str, - region: str, - database_rid: str, - collection_rid: str, - partition_key_range_id: str, - filter: str, - **kwargs: Any - ) -> Iterable["_models.PartitionMetric"]: - """Retrieves the metrics determined by the given filter for the given partition key range id and - region. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param region: Cosmos DB region, with spaces between words and each word capitalized. Required. - :type region: str - :param database_rid: Cosmos DB database rid. Required. - :type database_rid: str - :param collection_rid: Cosmos DB collection rid. Required. - :type collection_rid: str - :param partition_key_range_id: Partition Key Range Id for which to get data. Required. - :type partition_key_range_id: str - :param filter: An OData filter expression that describes a subset of metrics to return. The - parameters that can be filtered are name.value (name of the metric, can have an or of multiple - names), startTime, endTime, and timeGrain. The supported operator is eq. Required. - :type filter: str - :return: An iterator like instance of either PartitionMetric or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.PartitionMetric] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.PartitionMetricListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_metrics_request( - resource_group_name=resource_group_name, - account_name=account_name, - region=region, - database_rid=database_rid, - collection_rid=collection_rid, - partition_key_range_id=partition_key_range_id, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PartitionMetricListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_metrics_request( + resource_group_name: str, + account_name: str, + region: str, + database_rid: str, + collection_rid: str, + partition_key_range_id: str, + subscription_id: str, + *, + filter: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/region/{region}/databases/{databaseRid}/collections/{collectionRid}/partitionKeyRangeId/{partitionKeyRangeId}/metrics", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "region": _SERIALIZER.url("region", region, "str"), + "databaseRid": _SERIALIZER.url("database_rid", database_rid, "str"), + "collectionRid": _SERIALIZER.url("collection_rid", collection_rid, "str"), + "partitionKeyRangeId": _SERIALIZER.url("partition_key_range_id", partition_key_range_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class PartitionKeyRangeIdRegionOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`partition_key_range_id_region` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_metrics( + self, + resource_group_name: str, + account_name: str, + region: str, + database_rid: str, + collection_rid: str, + partition_key_range_id: str, + filter: str, + **kwargs: Any + ) -> Iterable["_models.PartitionMetric"]: + """Retrieves the metrics determined by the given filter for the given partition key range id and + region. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param region: Cosmos DB region, with spaces between words and each word capitalized. Required. + :type region: str + :param database_rid: Cosmos DB database rid. Required. + :type database_rid: str + :param collection_rid: Cosmos DB collection rid. Required. + :type collection_rid: str + :param partition_key_range_id: Partition Key Range Id for which to get data. Required. + :type partition_key_range_id: str + :param filter: An OData filter expression that describes a subset of metrics to return. The + parameters that can be filtered are name.value (name of the metric, can have an or of multiple + names), startTime, endTime, and timeGrain. The supported operator is eq. Required. + :type filter: str + :return: An iterator like instance of either PartitionMetric or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.PartitionMetric] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PartitionMetricListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_metrics_request( + resource_group_name=resource_group_name, + account_name=account_name, + region=region, + database_rid=database_rid, + collection_rid=collection_rid, + partition_key_range_id=partition_key_range_id, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PartitionMetricListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_patch.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_patch.py index 1bb0db275de..f7dd3251033 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_patch.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_patch.py @@ -1,20 +1,20 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_percentile_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_percentile_operations.py index 4c0e16339de..556611756b6 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_percentile_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_percentile_operations.py @@ -1,184 +1,184 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_metrics_request( - resource_group_name: str, account_name: str, subscription_id: str, *, filter: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/percentile/metrics", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class PercentileOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`percentile` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_metrics( - self, resource_group_name: str, account_name: str, filter: str, **kwargs: Any - ) -> Iterable["_models.PercentileMetric"]: - """Retrieves the metrics determined by the given filter for the given database account. This url - is only for PBS and Replication Latency data. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param filter: An OData filter expression that describes a subset of metrics to return. The - parameters that can be filtered are name.value (name of the metric, can have an or of multiple - names), startTime, endTime, and timeGrain. The supported operator is eq. Required. - :type filter: str - :return: An iterator like instance of either PercentileMetric or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.PercentileMetric] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.PercentileMetricListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_metrics_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PercentileMetricListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_metrics_request( + resource_group_name: str, account_name: str, subscription_id: str, *, filter: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/percentile/metrics", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class PercentileOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`percentile` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_metrics( + self, resource_group_name: str, account_name: str, filter: str, **kwargs: Any + ) -> Iterable["_models.PercentileMetric"]: + """Retrieves the metrics determined by the given filter for the given database account. This url + is only for PBS and Replication Latency data. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param filter: An OData filter expression that describes a subset of metrics to return. The + parameters that can be filtered are name.value (name of the metric, can have an or of multiple + names), startTime, endTime, and timeGrain. The supported operator is eq. Required. + :type filter: str + :return: An iterator like instance of either PercentileMetric or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.PercentileMetric] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PercentileMetricListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_metrics_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PercentileMetricListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_percentile_source_target_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_percentile_source_target_operations.py index 09a880d2abb..95b68047056 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_percentile_source_target_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_percentile_source_target_operations.py @@ -1,207 +1,207 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_metrics_request( - resource_group_name: str, - account_name: str, - source_region: str, - target_region: str, - subscription_id: str, - *, - filter: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sourceRegion/{sourceRegion}/targetRegion/{targetRegion}/percentile/metrics", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "sourceRegion": _SERIALIZER.url("source_region", source_region, "str"), - "targetRegion": _SERIALIZER.url("target_region", target_region, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class PercentileSourceTargetOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`percentile_source_target` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_metrics( - self, - resource_group_name: str, - account_name: str, - source_region: str, - target_region: str, - filter: str, - **kwargs: Any - ) -> Iterable["_models.PercentileMetric"]: - """Retrieves the metrics determined by the given filter for the given account, source and target - region. This url is only for PBS and Replication Latency data. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param source_region: Source region from which data is written. Cosmos DB region, with spaces - between words and each word capitalized. Required. - :type source_region: str - :param target_region: Target region to which data is written. Cosmos DB region, with spaces - between words and each word capitalized. Required. - :type target_region: str - :param filter: An OData filter expression that describes a subset of metrics to return. The - parameters that can be filtered are name.value (name of the metric, can have an or of multiple - names), startTime, endTime, and timeGrain. The supported operator is eq. Required. - :type filter: str - :return: An iterator like instance of either PercentileMetric or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.PercentileMetric] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.PercentileMetricListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_metrics_request( - resource_group_name=resource_group_name, - account_name=account_name, - source_region=source_region, - target_region=target_region, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PercentileMetricListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_metrics_request( + resource_group_name: str, + account_name: str, + source_region: str, + target_region: str, + subscription_id: str, + *, + filter: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sourceRegion/{sourceRegion}/targetRegion/{targetRegion}/percentile/metrics", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "sourceRegion": _SERIALIZER.url("source_region", source_region, "str"), + "targetRegion": _SERIALIZER.url("target_region", target_region, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class PercentileSourceTargetOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`percentile_source_target` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_metrics( + self, + resource_group_name: str, + account_name: str, + source_region: str, + target_region: str, + filter: str, + **kwargs: Any + ) -> Iterable["_models.PercentileMetric"]: + """Retrieves the metrics determined by the given filter for the given account, source and target + region. This url is only for PBS and Replication Latency data. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param source_region: Source region from which data is written. Cosmos DB region, with spaces + between words and each word capitalized. Required. + :type source_region: str + :param target_region: Target region to which data is written. Cosmos DB region, with spaces + between words and each word capitalized. Required. + :type target_region: str + :param filter: An OData filter expression that describes a subset of metrics to return. The + parameters that can be filtered are name.value (name of the metric, can have an or of multiple + names), startTime, endTime, and timeGrain. The supported operator is eq. Required. + :type filter: str + :return: An iterator like instance of either PercentileMetric or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.PercentileMetric] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PercentileMetricListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_metrics_request( + resource_group_name=resource_group_name, + account_name=account_name, + source_region=source_region, + target_region=target_region, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PercentileMetricListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_percentile_target_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_percentile_target_operations.py index a83a3e58837..cf59ddf0d28 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_percentile_target_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_percentile_target_operations.py @@ -1,189 +1,189 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_metrics_request( - resource_group_name: str, account_name: str, target_region: str, subscription_id: str, *, filter: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/targetRegion/{targetRegion}/percentile/metrics", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "targetRegion": _SERIALIZER.url("target_region", target_region, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class PercentileTargetOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`percentile_target` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_metrics( - self, resource_group_name: str, account_name: str, target_region: str, filter: str, **kwargs: Any - ) -> Iterable["_models.PercentileMetric"]: - """Retrieves the metrics determined by the given filter for the given account target region. This - url is only for PBS and Replication Latency data. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param target_region: Target region to which data is written. Cosmos DB region, with spaces - between words and each word capitalized. Required. - :type target_region: str - :param filter: An OData filter expression that describes a subset of metrics to return. The - parameters that can be filtered are name.value (name of the metric, can have an or of multiple - names), startTime, endTime, and timeGrain. The supported operator is eq. Required. - :type filter: str - :return: An iterator like instance of either PercentileMetric or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.PercentileMetric] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.PercentileMetricListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_metrics_request( - resource_group_name=resource_group_name, - account_name=account_name, - target_region=target_region, - subscription_id=self._config.subscription_id, - filter=filter, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PercentileMetricListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_metrics_request( + resource_group_name: str, account_name: str, target_region: str, subscription_id: str, *, filter: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/targetRegion/{targetRegion}/percentile/metrics", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "targetRegion": _SERIALIZER.url("target_region", target_region, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class PercentileTargetOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`percentile_target` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_metrics( + self, resource_group_name: str, account_name: str, target_region: str, filter: str, **kwargs: Any + ) -> Iterable["_models.PercentileMetric"]: + """Retrieves the metrics determined by the given filter for the given account target region. This + url is only for PBS and Replication Latency data. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param target_region: Target region to which data is written. Cosmos DB region, with spaces + between words and each word capitalized. Required. + :type target_region: str + :param filter: An OData filter expression that describes a subset of metrics to return. The + parameters that can be filtered are name.value (name of the metric, can have an or of multiple + names), startTime, endTime, and timeGrain. The supported operator is eq. Required. + :type filter: str + :return: An iterator like instance of either PercentileMetric or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.PercentileMetric] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PercentileMetricListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_metrics_request( + resource_group_name=resource_group_name, + account_name=account_name, + target_region=target_region, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PercentileMetricListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_private_endpoint_connections_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_private_endpoint_connections_operations.py index f68a4a3e239..8297bde07a2 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_private_endpoint_connections_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_private_endpoint_connections_operations.py @@ -1,686 +1,686 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.arm_polling import ARMPolling - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_by_database_account_request( - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/privateEndpointConnections", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request( - resource_group_name: str, - account_name: str, - private_endpoint_connection_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "privateEndpointConnectionName": _SERIALIZER.url( - "private_endpoint_connection_name", private_endpoint_connection_name, "str" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_or_update_request( - resource_group_name: str, - account_name: str, - private_endpoint_connection_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "privateEndpointConnectionName": _SERIALIZER.url( - "private_endpoint_connection_name", private_endpoint_connection_name, "str" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - resource_group_name: str, - account_name: str, - private_endpoint_connection_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "privateEndpointConnectionName": _SERIALIZER.url( - "private_endpoint_connection_name", private_endpoint_connection_name, "str" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -class PrivateEndpointConnectionsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`private_endpoint_connections` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_by_database_account( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> Iterable["_models.PrivateEndpointConnection"]: - """List all private endpoint connections on a Cosmos DB account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either PrivateEndpointConnection or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.PrivateEndpointConnection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.PrivateEndpointConnectionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_by_database_account_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PrivateEndpointConnectionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get( - self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, **kwargs: Any - ) -> _models.PrivateEndpointConnection: - """Gets a private endpoint connection. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection. Required. - :type private_endpoint_connection_name: str - :return: PrivateEndpointConnection or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.PrivateEndpointConnection - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - account_name=account_name, - private_endpoint_connection_name=private_endpoint_connection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _create_or_update_initial( - self, - resource_group_name: str, - account_name: str, - private_endpoint_connection_name: str, - parameters: Union[_models.PrivateEndpointConnection, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PrivateEndpointConnection") - - _request = build_create_or_update_request( - resource_group_name=resource_group_name, - account_name=account_name, - private_endpoint_connection_name=private_endpoint_connection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_or_update( - self, - resource_group_name: str, - account_name: str, - private_endpoint_connection_name: str, - parameters: _models.PrivateEndpointConnection, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.PrivateEndpointConnection]: - """Approve or reject a private endpoint connection with a given name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection. Required. - :type private_endpoint_connection_name: str - :param parameters: Required. - :type parameters: ~azure.mgmt.cosmosdb.models.PrivateEndpointConnection - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result - of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PrivateEndpointConnection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_or_update( - self, - resource_group_name: str, - account_name: str, - private_endpoint_connection_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.PrivateEndpointConnection]: - """Approve or reject a private endpoint connection with a given name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection. Required. - :type private_endpoint_connection_name: str - :param parameters: Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result - of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PrivateEndpointConnection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_or_update( - self, - resource_group_name: str, - account_name: str, - private_endpoint_connection_name: str, - parameters: Union[_models.PrivateEndpointConnection, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.PrivateEndpointConnection]: - """Approve or reject a private endpoint connection with a given name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection. Required. - :type private_endpoint_connection_name: str - :param parameters: Is either a PrivateEndpointConnection type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.cosmosdb.models.PrivateEndpointConnection or IO[bytes] - :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result - of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PrivateEndpointConnection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_or_update_initial( - resource_group_name=resource_group_name, - account_name=account_name, - private_endpoint_connection_name=private_endpoint_connection_name, - parameters=parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.PrivateEndpointConnection].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.PrivateEndpointConnection]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _delete_initial( - self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - account_name=account_name, - private_endpoint_connection_name=private_endpoint_connection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete( - self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, **kwargs: Any - ) -> LROPoller[None]: - """Deletes a private endpoint connection with a given name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection. Required. - :type private_endpoint_connection_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_initial( - resource_group_name=resource_group_name, - account_name=account_name, - private_endpoint_connection_name=private_endpoint_connection_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_by_database_account_request( + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/privateEndpointConnections", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request( + resource_group_name: str, + account_name: str, + private_endpoint_connection_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "privateEndpointConnectionName": _SERIALIZER.url( + "private_endpoint_connection_name", private_endpoint_connection_name, "str" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request( + resource_group_name: str, + account_name: str, + private_endpoint_connection_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "privateEndpointConnectionName": _SERIALIZER.url( + "private_endpoint_connection_name", private_endpoint_connection_name, "str" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, + account_name: str, + private_endpoint_connection_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "privateEndpointConnectionName": _SERIALIZER.url( + "private_endpoint_connection_name", private_endpoint_connection_name, "str" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +class PrivateEndpointConnectionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`private_endpoint_connections` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_by_database_account( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> Iterable["_models.PrivateEndpointConnection"]: + """List all private endpoint connections on a Cosmos DB account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either PrivateEndpointConnection or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PrivateEndpointConnectionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_database_account_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PrivateEndpointConnectionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get( + self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, **kwargs: Any + ) -> _models.PrivateEndpointConnection: + """Gets a private endpoint connection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :return: PrivateEndpointConnection or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.PrivateEndpointConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + account_name=account_name, + private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_or_update_initial( + self, + resource_group_name: str, + account_name: str, + private_endpoint_connection_name: str, + parameters: Union[_models.PrivateEndpointConnection, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PrivateEndpointConnection") + + _request = build_create_or_update_request( + resource_group_name=resource_group_name, + account_name=account_name, + private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + account_name: str, + private_endpoint_connection_name: str, + parameters: _models.PrivateEndpointConnection, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PrivateEndpointConnection]: + """Approve or reject a private endpoint connection with a given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :param parameters: Required. + :type parameters: ~azure.mgmt.cosmosdb.models.PrivateEndpointConnection + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + account_name: str, + private_endpoint_connection_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PrivateEndpointConnection]: + """Approve or reject a private endpoint connection with a given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :param parameters: Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + account_name: str, + private_endpoint_connection_name: str, + parameters: Union[_models.PrivateEndpointConnection, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.PrivateEndpointConnection]: + """Approve or reject a private endpoint connection with a given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :param parameters: Is either a PrivateEndpointConnection type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.cosmosdb.models.PrivateEndpointConnection or IO[bytes] + :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + account_name=account_name, + private_endpoint_connection_name=private_endpoint_connection_name, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.PrivateEndpointConnection].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.PrivateEndpointConnection]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_initial( + self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + account_name=account_name, + private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete( + self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Deletes a private endpoint connection with a given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + account_name=account_name, + private_endpoint_connection_name=private_endpoint_connection_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_private_link_resources_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_private_link_resources_operations.py index 37ff1169480..ce438e6a78e 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_private_link_resources_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_private_link_resources_operations.py @@ -1,273 +1,273 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_by_database_account_request( - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/privateLinkResources", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request( - resource_group_name: str, account_name: str, group_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/privateLinkResources/{groupName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "groupName": _SERIALIZER.url("group_name", group_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class PrivateLinkResourcesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`private_link_resources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_by_database_account( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> Iterable["_models.PrivateLinkResource"]: - """Gets the private link resources that need to be created for a Cosmos DB account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either PrivateLinkResource or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.PrivateLinkResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.PrivateLinkResourceListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_by_database_account_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PrivateLinkResourceListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get( - self, resource_group_name: str, account_name: str, group_name: str, **kwargs: Any - ) -> _models.PrivateLinkResource: - """Gets the private link resources that need to be created for a Cosmos DB account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param group_name: The name of the private link resource. Required. - :type group_name: str - :return: PrivateLinkResource or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.PrivateLinkResource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.PrivateLinkResource] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - account_name=account_name, - group_name=group_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PrivateLinkResource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_by_database_account_request( + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/privateLinkResources", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request( + resource_group_name: str, account_name: str, group_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/privateLinkResources/{groupName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "groupName": _SERIALIZER.url("group_name", group_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class PrivateLinkResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`private_link_resources` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_by_database_account( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> Iterable["_models.PrivateLinkResource"]: + """Gets the private link resources that need to be created for a Cosmos DB account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either PrivateLinkResource or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.PrivateLinkResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PrivateLinkResourceListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_database_account_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PrivateLinkResourceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get( + self, resource_group_name: str, account_name: str, group_name: str, **kwargs: Any + ) -> _models.PrivateLinkResource: + """Gets the private link resources that need to be created for a Cosmos DB account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param group_name: The name of the private link resource. Required. + :type group_name: str + :return: PrivateLinkResource or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.PrivateLinkResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PrivateLinkResource] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + account_name=account_name, + group_name=group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PrivateLinkResource", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_database_accounts_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_database_accounts_operations.py index 090678d498a..fe1cdb179e4 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_database_accounts_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_database_accounts_operations.py @@ -1,359 +1,359 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_by_location_request(location: str, subscription_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "location": _SERIALIZER.url("location", location, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/restorableDatabaseAccounts" - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_by_location_request(location: str, instance_id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{instanceId}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "location": _SERIALIZER.url("location", location, "str"), - "instanceId": _SERIALIZER.url("instance_id", instance_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class RestorableDatabaseAccountsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`restorable_database_accounts` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_by_location(self, location: str, **kwargs: Any) -> Iterable["_models.RestorableDatabaseAccountGetResult"]: - """Lists all the restorable Azure Cosmos DB database accounts available under the subscription and - in a region. This call requires - 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/read' permission. - - :param location: Cosmos DB region, with spaces between words and each word capitalized. - Required. - :type location: str - :return: An iterator like instance of either RestorableDatabaseAccountGetResult or the result - of cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.RestorableDatabaseAccountGetResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.RestorableDatabaseAccountsListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_by_location_request( - location=location, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("RestorableDatabaseAccountsListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list(self, **kwargs: Any) -> Iterable["_models.RestorableDatabaseAccountGetResult"]: - """Lists all the restorable Azure Cosmos DB database accounts available under the subscription. - This call requires 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/read' permission. - - :return: An iterator like instance of either RestorableDatabaseAccountGetResult or the result - of cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.RestorableDatabaseAccountGetResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.RestorableDatabaseAccountsListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("RestorableDatabaseAccountsListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get_by_location( - self, location: str, instance_id: str, **kwargs: Any - ) -> _models.RestorableDatabaseAccountGetResult: - """Retrieves the properties of an existing Azure Cosmos DB restorable database account. This call - requires 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/read/*' permission. - - :param location: Cosmos DB region, with spaces between words and each word capitalized. - Required. - :type location: str - :param instance_id: The instanceId GUID of a restorable database account. Required. - :type instance_id: str - :return: RestorableDatabaseAccountGetResult or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.RestorableDatabaseAccountGetResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.RestorableDatabaseAccountGetResult] = kwargs.pop("cls", None) - - _request = build_get_by_location_request( - location=location, - instance_id=instance_id, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("RestorableDatabaseAccountGetResult", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_by_location_request(location: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "location": _SERIALIZER.url("location", location, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/restorableDatabaseAccounts" + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_location_request(location: str, instance_id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{instanceId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "location": _SERIALIZER.url("location", location, "str"), + "instanceId": _SERIALIZER.url("instance_id", instance_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RestorableDatabaseAccountsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`restorable_database_accounts` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_by_location(self, location: str, **kwargs: Any) -> Iterable["_models.RestorableDatabaseAccountGetResult"]: + """Lists all the restorable Azure Cosmos DB database accounts available under the subscription and + in a region. This call requires + 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/read' permission. + + :param location: Cosmos DB region, with spaces between words and each word capitalized. + Required. + :type location: str + :return: An iterator like instance of either RestorableDatabaseAccountGetResult or the result + of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.RestorableDatabaseAccountGetResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RestorableDatabaseAccountsListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_location_request( + location=location, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RestorableDatabaseAccountsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.RestorableDatabaseAccountGetResult"]: + """Lists all the restorable Azure Cosmos DB database accounts available under the subscription. + This call requires 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/read' permission. + + :return: An iterator like instance of either RestorableDatabaseAccountGetResult or the result + of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.RestorableDatabaseAccountGetResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RestorableDatabaseAccountsListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RestorableDatabaseAccountsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get_by_location( + self, location: str, instance_id: str, **kwargs: Any + ) -> _models.RestorableDatabaseAccountGetResult: + """Retrieves the properties of an existing Azure Cosmos DB restorable database account. This call + requires 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/read/*' permission. + + :param location: Cosmos DB region, with spaces between words and each word capitalized. + Required. + :type location: str + :param instance_id: The instanceId GUID of a restorable database account. Required. + :type instance_id: str + :return: RestorableDatabaseAccountGetResult or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.RestorableDatabaseAccountGetResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RestorableDatabaseAccountGetResult] = kwargs.pop("cls", None) + + _request = build_get_by_location_request( + location=location, + instance_id=instance_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RestorableDatabaseAccountGetResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_gremlin_databases_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_gremlin_databases_operations.py index d69107fcb92..4954ecb3144 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_gremlin_databases_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_gremlin_databases_operations.py @@ -1,176 +1,176 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_request(location: str, instance_id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{instanceId}/restorableGremlinDatabases", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "location": _SERIALIZER.url("location", location, "str"), - "instanceId": _SERIALIZER.url("instance_id", instance_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class RestorableGremlinDatabasesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`restorable_gremlin_databases` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, location: str, instance_id: str, **kwargs: Any - ) -> Iterable["_models.RestorableGremlinDatabaseGetResult"]: - """Show the event feed of all mutations done on all the Azure Cosmos DB Gremlin databases under - the restorable account. This helps in scenario where database was accidentally deleted to get - the deletion time. This API requires - 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. - - :param location: Cosmos DB region, with spaces between words and each word capitalized. - Required. - :type location: str - :param instance_id: The instanceId GUID of a restorable database account. Required. - :type instance_id: str - :return: An iterator like instance of either RestorableGremlinDatabaseGetResult or the result - of cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.RestorableGremlinDatabaseGetResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.RestorableGremlinDatabasesListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - location=location, - instance_id=instance_id, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("RestorableGremlinDatabasesListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(location: str, instance_id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{instanceId}/restorableGremlinDatabases", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "location": _SERIALIZER.url("location", location, "str"), + "instanceId": _SERIALIZER.url("instance_id", instance_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RestorableGremlinDatabasesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`restorable_gremlin_databases` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, location: str, instance_id: str, **kwargs: Any + ) -> Iterable["_models.RestorableGremlinDatabaseGetResult"]: + """Show the event feed of all mutations done on all the Azure Cosmos DB Gremlin databases under + the restorable account. This helps in scenario where database was accidentally deleted to get + the deletion time. This API requires + 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. + + :param location: Cosmos DB region, with spaces between words and each word capitalized. + Required. + :type location: str + :param instance_id: The instanceId GUID of a restorable database account. Required. + :type instance_id: str + :return: An iterator like instance of either RestorableGremlinDatabaseGetResult or the result + of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.RestorableGremlinDatabaseGetResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RestorableGremlinDatabasesListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + location=location, + instance_id=instance_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RestorableGremlinDatabasesListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_gremlin_graphs_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_gremlin_graphs_operations.py index 01ad9214aa4..2a0cb958b43 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_gremlin_graphs_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_gremlin_graphs_operations.py @@ -1,208 +1,208 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_request( - location: str, - instance_id: str, - subscription_id: str, - *, - restorable_gremlin_database_rid: Optional[str] = None, - start_time: Optional[str] = None, - end_time: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{instanceId}/restorableGraphs", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "location": _SERIALIZER.url("location", location, "str"), - "instanceId": _SERIALIZER.url("instance_id", instance_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if restorable_gremlin_database_rid is not None: - _params["restorableGremlinDatabaseRid"] = _SERIALIZER.query( - "restorable_gremlin_database_rid", restorable_gremlin_database_rid, "str" - ) - if start_time is not None: - _params["startTime"] = _SERIALIZER.query("start_time", start_time, "str") - if end_time is not None: - _params["endTime"] = _SERIALIZER.query("end_time", end_time, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class RestorableGremlinGraphsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`restorable_gremlin_graphs` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, - location: str, - instance_id: str, - restorable_gremlin_database_rid: Optional[str] = None, - start_time: Optional[str] = None, - end_time: Optional[str] = None, - **kwargs: Any - ) -> Iterable["_models.RestorableGremlinGraphGetResult"]: - """Show the event feed of all mutations done on all the Azure Cosmos DB Gremlin graphs under a - specific database. This helps in scenario where container was accidentally deleted. This API - requires 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. - - :param location: Cosmos DB region, with spaces between words and each word capitalized. - Required. - :type location: str - :param instance_id: The instanceId GUID of a restorable database account. Required. - :type instance_id: str - :param restorable_gremlin_database_rid: The resource ID of the Gremlin database. Default value - is None. - :type restorable_gremlin_database_rid: str - :param start_time: Restorable Gremlin graphs event feed start time. Default value is None. - :type start_time: str - :param end_time: Restorable Gremlin graphs event feed end time. Default value is None. - :type end_time: str - :return: An iterator like instance of either RestorableGremlinGraphGetResult or the result of - cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.RestorableGremlinGraphGetResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.RestorableGremlinGraphsListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - location=location, - instance_id=instance_id, - subscription_id=self._config.subscription_id, - restorable_gremlin_database_rid=restorable_gremlin_database_rid, - start_time=start_time, - end_time=end_time, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("RestorableGremlinGraphsListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request( + location: str, + instance_id: str, + subscription_id: str, + *, + restorable_gremlin_database_rid: Optional[str] = None, + start_time: Optional[str] = None, + end_time: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{instanceId}/restorableGraphs", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "location": _SERIALIZER.url("location", location, "str"), + "instanceId": _SERIALIZER.url("instance_id", instance_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if restorable_gremlin_database_rid is not None: + _params["restorableGremlinDatabaseRid"] = _SERIALIZER.query( + "restorable_gremlin_database_rid", restorable_gremlin_database_rid, "str" + ) + if start_time is not None: + _params["startTime"] = _SERIALIZER.query("start_time", start_time, "str") + if end_time is not None: + _params["endTime"] = _SERIALIZER.query("end_time", end_time, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RestorableGremlinGraphsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`restorable_gremlin_graphs` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, + location: str, + instance_id: str, + restorable_gremlin_database_rid: Optional[str] = None, + start_time: Optional[str] = None, + end_time: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.RestorableGremlinGraphGetResult"]: + """Show the event feed of all mutations done on all the Azure Cosmos DB Gremlin graphs under a + specific database. This helps in scenario where container was accidentally deleted. This API + requires 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. + + :param location: Cosmos DB region, with spaces between words and each word capitalized. + Required. + :type location: str + :param instance_id: The instanceId GUID of a restorable database account. Required. + :type instance_id: str + :param restorable_gremlin_database_rid: The resource ID of the Gremlin database. Default value + is None. + :type restorable_gremlin_database_rid: str + :param start_time: Restorable Gremlin graphs event feed start time. Default value is None. + :type start_time: str + :param end_time: Restorable Gremlin graphs event feed end time. Default value is None. + :type end_time: str + :return: An iterator like instance of either RestorableGremlinGraphGetResult or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.RestorableGremlinGraphGetResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RestorableGremlinGraphsListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + location=location, + instance_id=instance_id, + subscription_id=self._config.subscription_id, + restorable_gremlin_database_rid=restorable_gremlin_database_rid, + start_time=start_time, + end_time=end_time, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RestorableGremlinGraphsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_gremlin_resources_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_gremlin_resources_operations.py index 4a0b3f88184..45558c30aa1 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_gremlin_resources_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_gremlin_resources_operations.py @@ -1,203 +1,203 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_request( - location: str, - instance_id: str, - subscription_id: str, - *, - restore_location: Optional[str] = None, - restore_timestamp_in_utc: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{instanceId}/restorableGremlinResources", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "location": _SERIALIZER.url("location", location, "str"), - "instanceId": _SERIALIZER.url("instance_id", instance_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if restore_location is not None: - _params["restoreLocation"] = _SERIALIZER.query("restore_location", restore_location, "str") - if restore_timestamp_in_utc is not None: - _params["restoreTimestampInUtc"] = _SERIALIZER.query( - "restore_timestamp_in_utc", restore_timestamp_in_utc, "str" - ) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class RestorableGremlinResourcesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`restorable_gremlin_resources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, - location: str, - instance_id: str, - restore_location: Optional[str] = None, - restore_timestamp_in_utc: Optional[str] = None, - **kwargs: Any - ) -> Iterable["_models.RestorableGremlinResourcesGetResult"]: - """Return a list of gremlin database and graphs combo that exist on the account at the given - timestamp and location. This helps in scenarios to validate what resources exist at given - timestamp and location. This API requires - 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. - - :param location: Cosmos DB region, with spaces between words and each word capitalized. - Required. - :type location: str - :param instance_id: The instanceId GUID of a restorable database account. Required. - :type instance_id: str - :param restore_location: The location where the restorable resources are located. Default value - is None. - :type restore_location: str - :param restore_timestamp_in_utc: The timestamp when the restorable resources existed. Default - value is None. - :type restore_timestamp_in_utc: str - :return: An iterator like instance of either RestorableGremlinResourcesGetResult or the result - of cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.RestorableGremlinResourcesGetResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.RestorableGremlinResourcesListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - location=location, - instance_id=instance_id, - subscription_id=self._config.subscription_id, - restore_location=restore_location, - restore_timestamp_in_utc=restore_timestamp_in_utc, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("RestorableGremlinResourcesListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request( + location: str, + instance_id: str, + subscription_id: str, + *, + restore_location: Optional[str] = None, + restore_timestamp_in_utc: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{instanceId}/restorableGremlinResources", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "location": _SERIALIZER.url("location", location, "str"), + "instanceId": _SERIALIZER.url("instance_id", instance_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if restore_location is not None: + _params["restoreLocation"] = _SERIALIZER.query("restore_location", restore_location, "str") + if restore_timestamp_in_utc is not None: + _params["restoreTimestampInUtc"] = _SERIALIZER.query( + "restore_timestamp_in_utc", restore_timestamp_in_utc, "str" + ) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RestorableGremlinResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`restorable_gremlin_resources` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, + location: str, + instance_id: str, + restore_location: Optional[str] = None, + restore_timestamp_in_utc: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.RestorableGremlinResourcesGetResult"]: + """Return a list of gremlin database and graphs combo that exist on the account at the given + timestamp and location. This helps in scenarios to validate what resources exist at given + timestamp and location. This API requires + 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. + + :param location: Cosmos DB region, with spaces between words and each word capitalized. + Required. + :type location: str + :param instance_id: The instanceId GUID of a restorable database account. Required. + :type instance_id: str + :param restore_location: The location where the restorable resources are located. Default value + is None. + :type restore_location: str + :param restore_timestamp_in_utc: The timestamp when the restorable resources existed. Default + value is None. + :type restore_timestamp_in_utc: str + :return: An iterator like instance of either RestorableGremlinResourcesGetResult or the result + of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.RestorableGremlinResourcesGetResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RestorableGremlinResourcesListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + location=location, + instance_id=instance_id, + subscription_id=self._config.subscription_id, + restore_location=restore_location, + restore_timestamp_in_utc=restore_timestamp_in_utc, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RestorableGremlinResourcesListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_mongodb_collections_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_mongodb_collections_operations.py index b0318cd6317..9e9274bdaaa 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_mongodb_collections_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_mongodb_collections_operations.py @@ -1,208 +1,208 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_request( - location: str, - instance_id: str, - subscription_id: str, - *, - restorable_mongodb_database_rid: Optional[str] = None, - start_time: Optional[str] = None, - end_time: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{instanceId}/restorableMongodbCollections", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "location": _SERIALIZER.url("location", location, "str"), - "instanceId": _SERIALIZER.url("instance_id", instance_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if restorable_mongodb_database_rid is not None: - _params["restorableMongodbDatabaseRid"] = _SERIALIZER.query( - "restorable_mongodb_database_rid", restorable_mongodb_database_rid, "str" - ) - if start_time is not None: - _params["startTime"] = _SERIALIZER.query("start_time", start_time, "str") - if end_time is not None: - _params["endTime"] = _SERIALIZER.query("end_time", end_time, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class RestorableMongodbCollectionsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`restorable_mongodb_collections` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, - location: str, - instance_id: str, - restorable_mongodb_database_rid: Optional[str] = None, - start_time: Optional[str] = None, - end_time: Optional[str] = None, - **kwargs: Any - ) -> Iterable["_models.RestorableMongodbCollectionGetResult"]: - """Show the event feed of all mutations done on all the Azure Cosmos DB MongoDB collections under - a specific database. This helps in scenario where container was accidentally deleted. This - API requires 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. - - :param location: Cosmos DB region, with spaces between words and each word capitalized. - Required. - :type location: str - :param instance_id: The instanceId GUID of a restorable database account. Required. - :type instance_id: str - :param restorable_mongodb_database_rid: The resource ID of the MongoDB database. Default value - is None. - :type restorable_mongodb_database_rid: str - :param start_time: Restorable MongoDB collections event feed start time. Default value is None. - :type start_time: str - :param end_time: Restorable MongoDB collections event feed end time. Default value is None. - :type end_time: str - :return: An iterator like instance of either RestorableMongodbCollectionGetResult or the result - of cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.RestorableMongodbCollectionGetResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.RestorableMongodbCollectionsListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - location=location, - instance_id=instance_id, - subscription_id=self._config.subscription_id, - restorable_mongodb_database_rid=restorable_mongodb_database_rid, - start_time=start_time, - end_time=end_time, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("RestorableMongodbCollectionsListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request( + location: str, + instance_id: str, + subscription_id: str, + *, + restorable_mongodb_database_rid: Optional[str] = None, + start_time: Optional[str] = None, + end_time: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{instanceId}/restorableMongodbCollections", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "location": _SERIALIZER.url("location", location, "str"), + "instanceId": _SERIALIZER.url("instance_id", instance_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if restorable_mongodb_database_rid is not None: + _params["restorableMongodbDatabaseRid"] = _SERIALIZER.query( + "restorable_mongodb_database_rid", restorable_mongodb_database_rid, "str" + ) + if start_time is not None: + _params["startTime"] = _SERIALIZER.query("start_time", start_time, "str") + if end_time is not None: + _params["endTime"] = _SERIALIZER.query("end_time", end_time, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RestorableMongodbCollectionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`restorable_mongodb_collections` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, + location: str, + instance_id: str, + restorable_mongodb_database_rid: Optional[str] = None, + start_time: Optional[str] = None, + end_time: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.RestorableMongodbCollectionGetResult"]: + """Show the event feed of all mutations done on all the Azure Cosmos DB MongoDB collections under + a specific database. This helps in scenario where container was accidentally deleted. This + API requires 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. + + :param location: Cosmos DB region, with spaces between words and each word capitalized. + Required. + :type location: str + :param instance_id: The instanceId GUID of a restorable database account. Required. + :type instance_id: str + :param restorable_mongodb_database_rid: The resource ID of the MongoDB database. Default value + is None. + :type restorable_mongodb_database_rid: str + :param start_time: Restorable MongoDB collections event feed start time. Default value is None. + :type start_time: str + :param end_time: Restorable MongoDB collections event feed end time. Default value is None. + :type end_time: str + :return: An iterator like instance of either RestorableMongodbCollectionGetResult or the result + of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.RestorableMongodbCollectionGetResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RestorableMongodbCollectionsListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + location=location, + instance_id=instance_id, + subscription_id=self._config.subscription_id, + restorable_mongodb_database_rid=restorable_mongodb_database_rid, + start_time=start_time, + end_time=end_time, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RestorableMongodbCollectionsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_mongodb_databases_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_mongodb_databases_operations.py index 2644ce4fe03..1cf1fadc3b8 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_mongodb_databases_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_mongodb_databases_operations.py @@ -1,176 +1,176 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_request(location: str, instance_id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{instanceId}/restorableMongodbDatabases", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "location": _SERIALIZER.url("location", location, "str"), - "instanceId": _SERIALIZER.url("instance_id", instance_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class RestorableMongodbDatabasesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`restorable_mongodb_databases` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, location: str, instance_id: str, **kwargs: Any - ) -> Iterable["_models.RestorableMongodbDatabaseGetResult"]: - """Show the event feed of all mutations done on all the Azure Cosmos DB MongoDB databases under - the restorable account. This helps in scenario where database was accidentally deleted to get - the deletion time. This API requires - 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. - - :param location: Cosmos DB region, with spaces between words and each word capitalized. - Required. - :type location: str - :param instance_id: The instanceId GUID of a restorable database account. Required. - :type instance_id: str - :return: An iterator like instance of either RestorableMongodbDatabaseGetResult or the result - of cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.RestorableMongodbDatabaseGetResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.RestorableMongodbDatabasesListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - location=location, - instance_id=instance_id, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("RestorableMongodbDatabasesListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(location: str, instance_id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{instanceId}/restorableMongodbDatabases", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "location": _SERIALIZER.url("location", location, "str"), + "instanceId": _SERIALIZER.url("instance_id", instance_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RestorableMongodbDatabasesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`restorable_mongodb_databases` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, location: str, instance_id: str, **kwargs: Any + ) -> Iterable["_models.RestorableMongodbDatabaseGetResult"]: + """Show the event feed of all mutations done on all the Azure Cosmos DB MongoDB databases under + the restorable account. This helps in scenario where database was accidentally deleted to get + the deletion time. This API requires + 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. + + :param location: Cosmos DB region, with spaces between words and each word capitalized. + Required. + :type location: str + :param instance_id: The instanceId GUID of a restorable database account. Required. + :type instance_id: str + :return: An iterator like instance of either RestorableMongodbDatabaseGetResult or the result + of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.RestorableMongodbDatabaseGetResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RestorableMongodbDatabasesListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + location=location, + instance_id=instance_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RestorableMongodbDatabasesListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_mongodb_resources_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_mongodb_resources_operations.py index e4e2f779a15..43293501d5e 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_mongodb_resources_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_mongodb_resources_operations.py @@ -1,203 +1,203 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_request( - location: str, - instance_id: str, - subscription_id: str, - *, - restore_location: Optional[str] = None, - restore_timestamp_in_utc: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{instanceId}/restorableMongodbResources", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "location": _SERIALIZER.url("location", location, "str"), - "instanceId": _SERIALIZER.url("instance_id", instance_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if restore_location is not None: - _params["restoreLocation"] = _SERIALIZER.query("restore_location", restore_location, "str") - if restore_timestamp_in_utc is not None: - _params["restoreTimestampInUtc"] = _SERIALIZER.query( - "restore_timestamp_in_utc", restore_timestamp_in_utc, "str" - ) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class RestorableMongodbResourcesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`restorable_mongodb_resources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, - location: str, - instance_id: str, - restore_location: Optional[str] = None, - restore_timestamp_in_utc: Optional[str] = None, - **kwargs: Any - ) -> Iterable["_models.RestorableMongodbResourcesGetResult"]: - """Return a list of database and collection combo that exist on the account at the given timestamp - and location. This helps in scenarios to validate what resources exist at given timestamp and - location. This API requires - 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. - - :param location: Cosmos DB region, with spaces between words and each word capitalized. - Required. - :type location: str - :param instance_id: The instanceId GUID of a restorable database account. Required. - :type instance_id: str - :param restore_location: The location where the restorable resources are located. Default value - is None. - :type restore_location: str - :param restore_timestamp_in_utc: The timestamp when the restorable resources existed. Default - value is None. - :type restore_timestamp_in_utc: str - :return: An iterator like instance of either RestorableMongodbResourcesGetResult or the result - of cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.RestorableMongodbResourcesGetResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.RestorableMongodbResourcesListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - location=location, - instance_id=instance_id, - subscription_id=self._config.subscription_id, - restore_location=restore_location, - restore_timestamp_in_utc=restore_timestamp_in_utc, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("RestorableMongodbResourcesListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request( + location: str, + instance_id: str, + subscription_id: str, + *, + restore_location: Optional[str] = None, + restore_timestamp_in_utc: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{instanceId}/restorableMongodbResources", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "location": _SERIALIZER.url("location", location, "str"), + "instanceId": _SERIALIZER.url("instance_id", instance_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if restore_location is not None: + _params["restoreLocation"] = _SERIALIZER.query("restore_location", restore_location, "str") + if restore_timestamp_in_utc is not None: + _params["restoreTimestampInUtc"] = _SERIALIZER.query( + "restore_timestamp_in_utc", restore_timestamp_in_utc, "str" + ) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RestorableMongodbResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`restorable_mongodb_resources` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, + location: str, + instance_id: str, + restore_location: Optional[str] = None, + restore_timestamp_in_utc: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.RestorableMongodbResourcesGetResult"]: + """Return a list of database and collection combo that exist on the account at the given timestamp + and location. This helps in scenarios to validate what resources exist at given timestamp and + location. This API requires + 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. + + :param location: Cosmos DB region, with spaces between words and each word capitalized. + Required. + :type location: str + :param instance_id: The instanceId GUID of a restorable database account. Required. + :type instance_id: str + :param restore_location: The location where the restorable resources are located. Default value + is None. + :type restore_location: str + :param restore_timestamp_in_utc: The timestamp when the restorable resources existed. Default + value is None. + :type restore_timestamp_in_utc: str + :return: An iterator like instance of either RestorableMongodbResourcesGetResult or the result + of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.RestorableMongodbResourcesGetResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RestorableMongodbResourcesListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + location=location, + instance_id=instance_id, + subscription_id=self._config.subscription_id, + restore_location=restore_location, + restore_timestamp_in_utc=restore_timestamp_in_utc, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RestorableMongodbResourcesListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_sql_containers_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_sql_containers_operations.py index 4e2af625dc3..ea8e34c0b64 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_sql_containers_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_sql_containers_operations.py @@ -1,207 +1,207 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_request( - location: str, - instance_id: str, - subscription_id: str, - *, - restorable_sql_database_rid: Optional[str] = None, - start_time: Optional[str] = None, - end_time: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{instanceId}/restorableSqlContainers", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "location": _SERIALIZER.url("location", location, "str"), - "instanceId": _SERIALIZER.url("instance_id", instance_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if restorable_sql_database_rid is not None: - _params["restorableSqlDatabaseRid"] = _SERIALIZER.query( - "restorable_sql_database_rid", restorable_sql_database_rid, "str" - ) - if start_time is not None: - _params["startTime"] = _SERIALIZER.query("start_time", start_time, "str") - if end_time is not None: - _params["endTime"] = _SERIALIZER.query("end_time", end_time, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class RestorableSqlContainersOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`restorable_sql_containers` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, - location: str, - instance_id: str, - restorable_sql_database_rid: Optional[str] = None, - start_time: Optional[str] = None, - end_time: Optional[str] = None, - **kwargs: Any - ) -> Iterable["_models.RestorableSqlContainerGetResult"]: - """Show the event feed of all mutations done on all the Azure Cosmos DB SQL containers under a - specific database. This helps in scenario where container was accidentally deleted. This API - requires 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. - - :param location: Cosmos DB region, with spaces between words and each word capitalized. - Required. - :type location: str - :param instance_id: The instanceId GUID of a restorable database account. Required. - :type instance_id: str - :param restorable_sql_database_rid: The resource ID of the SQL database. Default value is None. - :type restorable_sql_database_rid: str - :param start_time: Restorable Sql containers event feed start time. Default value is None. - :type start_time: str - :param end_time: Restorable Sql containers event feed end time. Default value is None. - :type end_time: str - :return: An iterator like instance of either RestorableSqlContainerGetResult or the result of - cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.RestorableSqlContainerGetResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.RestorableSqlContainersListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - location=location, - instance_id=instance_id, - subscription_id=self._config.subscription_id, - restorable_sql_database_rid=restorable_sql_database_rid, - start_time=start_time, - end_time=end_time, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("RestorableSqlContainersListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request( + location: str, + instance_id: str, + subscription_id: str, + *, + restorable_sql_database_rid: Optional[str] = None, + start_time: Optional[str] = None, + end_time: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{instanceId}/restorableSqlContainers", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "location": _SERIALIZER.url("location", location, "str"), + "instanceId": _SERIALIZER.url("instance_id", instance_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if restorable_sql_database_rid is not None: + _params["restorableSqlDatabaseRid"] = _SERIALIZER.query( + "restorable_sql_database_rid", restorable_sql_database_rid, "str" + ) + if start_time is not None: + _params["startTime"] = _SERIALIZER.query("start_time", start_time, "str") + if end_time is not None: + _params["endTime"] = _SERIALIZER.query("end_time", end_time, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RestorableSqlContainersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`restorable_sql_containers` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, + location: str, + instance_id: str, + restorable_sql_database_rid: Optional[str] = None, + start_time: Optional[str] = None, + end_time: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.RestorableSqlContainerGetResult"]: + """Show the event feed of all mutations done on all the Azure Cosmos DB SQL containers under a + specific database. This helps in scenario where container was accidentally deleted. This API + requires 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. + + :param location: Cosmos DB region, with spaces between words and each word capitalized. + Required. + :type location: str + :param instance_id: The instanceId GUID of a restorable database account. Required. + :type instance_id: str + :param restorable_sql_database_rid: The resource ID of the SQL database. Default value is None. + :type restorable_sql_database_rid: str + :param start_time: Restorable Sql containers event feed start time. Default value is None. + :type start_time: str + :param end_time: Restorable Sql containers event feed end time. Default value is None. + :type end_time: str + :return: An iterator like instance of either RestorableSqlContainerGetResult or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.RestorableSqlContainerGetResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RestorableSqlContainersListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + location=location, + instance_id=instance_id, + subscription_id=self._config.subscription_id, + restorable_sql_database_rid=restorable_sql_database_rid, + start_time=start_time, + end_time=end_time, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RestorableSqlContainersListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_sql_databases_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_sql_databases_operations.py index ca7b1c1f29d..b5ada9dbf2b 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_sql_databases_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_sql_databases_operations.py @@ -1,176 +1,176 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_request(location: str, instance_id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{instanceId}/restorableSqlDatabases", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "location": _SERIALIZER.url("location", location, "str"), - "instanceId": _SERIALIZER.url("instance_id", instance_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class RestorableSqlDatabasesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`restorable_sql_databases` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, location: str, instance_id: str, **kwargs: Any - ) -> Iterable["_models.RestorableSqlDatabaseGetResult"]: - """Show the event feed of all mutations done on all the Azure Cosmos DB SQL databases under the - restorable account. This helps in scenario where database was accidentally deleted to get the - deletion time. This API requires - 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. - - :param location: Cosmos DB region, with spaces between words and each word capitalized. - Required. - :type location: str - :param instance_id: The instanceId GUID of a restorable database account. Required. - :type instance_id: str - :return: An iterator like instance of either RestorableSqlDatabaseGetResult or the result of - cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.RestorableSqlDatabaseGetResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.RestorableSqlDatabasesListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - location=location, - instance_id=instance_id, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("RestorableSqlDatabasesListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(location: str, instance_id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{instanceId}/restorableSqlDatabases", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "location": _SERIALIZER.url("location", location, "str"), + "instanceId": _SERIALIZER.url("instance_id", instance_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RestorableSqlDatabasesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`restorable_sql_databases` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, location: str, instance_id: str, **kwargs: Any + ) -> Iterable["_models.RestorableSqlDatabaseGetResult"]: + """Show the event feed of all mutations done on all the Azure Cosmos DB SQL databases under the + restorable account. This helps in scenario where database was accidentally deleted to get the + deletion time. This API requires + 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. + + :param location: Cosmos DB region, with spaces between words and each word capitalized. + Required. + :type location: str + :param instance_id: The instanceId GUID of a restorable database account. Required. + :type instance_id: str + :return: An iterator like instance of either RestorableSqlDatabaseGetResult or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.RestorableSqlDatabaseGetResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RestorableSqlDatabasesListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + location=location, + instance_id=instance_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RestorableSqlDatabasesListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_sql_resources_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_sql_resources_operations.py index 14d10e10a68..ade7bd26431 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_sql_resources_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_sql_resources_operations.py @@ -1,203 +1,203 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_request( - location: str, - instance_id: str, - subscription_id: str, - *, - restore_location: Optional[str] = None, - restore_timestamp_in_utc: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{instanceId}/restorableSqlResources", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "location": _SERIALIZER.url("location", location, "str"), - "instanceId": _SERIALIZER.url("instance_id", instance_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if restore_location is not None: - _params["restoreLocation"] = _SERIALIZER.query("restore_location", restore_location, "str") - if restore_timestamp_in_utc is not None: - _params["restoreTimestampInUtc"] = _SERIALIZER.query( - "restore_timestamp_in_utc", restore_timestamp_in_utc, "str" - ) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class RestorableSqlResourcesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`restorable_sql_resources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, - location: str, - instance_id: str, - restore_location: Optional[str] = None, - restore_timestamp_in_utc: Optional[str] = None, - **kwargs: Any - ) -> Iterable["_models.RestorableSqlResourcesGetResult"]: - """Return a list of database and container combo that exist on the account at the given timestamp - and location. This helps in scenarios to validate what resources exist at given timestamp and - location. This API requires - 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. - - :param location: Cosmos DB region, with spaces between words and each word capitalized. - Required. - :type location: str - :param instance_id: The instanceId GUID of a restorable database account. Required. - :type instance_id: str - :param restore_location: The location where the restorable resources are located. Default value - is None. - :type restore_location: str - :param restore_timestamp_in_utc: The timestamp when the restorable resources existed. Default - value is None. - :type restore_timestamp_in_utc: str - :return: An iterator like instance of either RestorableSqlResourcesGetResult or the result of - cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.RestorableSqlResourcesGetResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.RestorableSqlResourcesListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - location=location, - instance_id=instance_id, - subscription_id=self._config.subscription_id, - restore_location=restore_location, - restore_timestamp_in_utc=restore_timestamp_in_utc, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("RestorableSqlResourcesListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request( + location: str, + instance_id: str, + subscription_id: str, + *, + restore_location: Optional[str] = None, + restore_timestamp_in_utc: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{instanceId}/restorableSqlResources", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "location": _SERIALIZER.url("location", location, "str"), + "instanceId": _SERIALIZER.url("instance_id", instance_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if restore_location is not None: + _params["restoreLocation"] = _SERIALIZER.query("restore_location", restore_location, "str") + if restore_timestamp_in_utc is not None: + _params["restoreTimestampInUtc"] = _SERIALIZER.query( + "restore_timestamp_in_utc", restore_timestamp_in_utc, "str" + ) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RestorableSqlResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`restorable_sql_resources` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, + location: str, + instance_id: str, + restore_location: Optional[str] = None, + restore_timestamp_in_utc: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.RestorableSqlResourcesGetResult"]: + """Return a list of database and container combo that exist on the account at the given timestamp + and location. This helps in scenarios to validate what resources exist at given timestamp and + location. This API requires + 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. + + :param location: Cosmos DB region, with spaces between words and each word capitalized. + Required. + :type location: str + :param instance_id: The instanceId GUID of a restorable database account. Required. + :type instance_id: str + :param restore_location: The location where the restorable resources are located. Default value + is None. + :type restore_location: str + :param restore_timestamp_in_utc: The timestamp when the restorable resources existed. Default + value is None. + :type restore_timestamp_in_utc: str + :return: An iterator like instance of either RestorableSqlResourcesGetResult or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.RestorableSqlResourcesGetResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RestorableSqlResourcesListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + location=location, + instance_id=instance_id, + subscription_id=self._config.subscription_id, + restore_location=restore_location, + restore_timestamp_in_utc=restore_timestamp_in_utc, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RestorableSqlResourcesListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_table_resources_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_table_resources_operations.py index 1f6a53b7577..a94ce0d3361 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_table_resources_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_table_resources_operations.py @@ -1,202 +1,202 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_request( - location: str, - instance_id: str, - subscription_id: str, - *, - restore_location: Optional[str] = None, - restore_timestamp_in_utc: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{instanceId}/restorableTableResources", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "location": _SERIALIZER.url("location", location, "str"), - "instanceId": _SERIALIZER.url("instance_id", instance_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if restore_location is not None: - _params["restoreLocation"] = _SERIALIZER.query("restore_location", restore_location, "str") - if restore_timestamp_in_utc is not None: - _params["restoreTimestampInUtc"] = _SERIALIZER.query( - "restore_timestamp_in_utc", restore_timestamp_in_utc, "str" - ) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class RestorableTableResourcesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`restorable_table_resources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, - location: str, - instance_id: str, - restore_location: Optional[str] = None, - restore_timestamp_in_utc: Optional[str] = None, - **kwargs: Any - ) -> Iterable["_models.RestorableTableResourcesGetResult"]: - """Return a list of tables that exist on the account at the given timestamp and location. This - helps in scenarios to validate what resources exist at given timestamp and location. This API - requires 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. - - :param location: Cosmos DB region, with spaces between words and each word capitalized. - Required. - :type location: str - :param instance_id: The instanceId GUID of a restorable database account. Required. - :type instance_id: str - :param restore_location: The location where the restorable resources are located. Default value - is None. - :type restore_location: str - :param restore_timestamp_in_utc: The timestamp when the restorable resources existed. Default - value is None. - :type restore_timestamp_in_utc: str - :return: An iterator like instance of either RestorableTableResourcesGetResult or the result of - cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.RestorableTableResourcesGetResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.RestorableTableResourcesListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - location=location, - instance_id=instance_id, - subscription_id=self._config.subscription_id, - restore_location=restore_location, - restore_timestamp_in_utc=restore_timestamp_in_utc, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("RestorableTableResourcesListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request( + location: str, + instance_id: str, + subscription_id: str, + *, + restore_location: Optional[str] = None, + restore_timestamp_in_utc: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{instanceId}/restorableTableResources", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "location": _SERIALIZER.url("location", location, "str"), + "instanceId": _SERIALIZER.url("instance_id", instance_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if restore_location is not None: + _params["restoreLocation"] = _SERIALIZER.query("restore_location", restore_location, "str") + if restore_timestamp_in_utc is not None: + _params["restoreTimestampInUtc"] = _SERIALIZER.query( + "restore_timestamp_in_utc", restore_timestamp_in_utc, "str" + ) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RestorableTableResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`restorable_table_resources` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, + location: str, + instance_id: str, + restore_location: Optional[str] = None, + restore_timestamp_in_utc: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.RestorableTableResourcesGetResult"]: + """Return a list of tables that exist on the account at the given timestamp and location. This + helps in scenarios to validate what resources exist at given timestamp and location. This API + requires 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. + + :param location: Cosmos DB region, with spaces between words and each word capitalized. + Required. + :type location: str + :param instance_id: The instanceId GUID of a restorable database account. Required. + :type instance_id: str + :param restore_location: The location where the restorable resources are located. Default value + is None. + :type restore_location: str + :param restore_timestamp_in_utc: The timestamp when the restorable resources existed. Default + value is None. + :type restore_timestamp_in_utc: str + :return: An iterator like instance of either RestorableTableResourcesGetResult or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.RestorableTableResourcesGetResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RestorableTableResourcesListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + location=location, + instance_id=instance_id, + subscription_id=self._config.subscription_id, + restore_location=restore_location, + restore_timestamp_in_utc=restore_timestamp_in_utc, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RestorableTableResourcesListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_tables_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_tables_operations.py index 5a95ceb67ee..6a15c7e67f0 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_tables_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_restorable_tables_operations.py @@ -1,197 +1,197 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_request( - location: str, - instance_id: str, - subscription_id: str, - *, - start_time: Optional[str] = None, - end_time: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{instanceId}/restorableTables", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "location": _SERIALIZER.url("location", location, "str"), - "instanceId": _SERIALIZER.url("instance_id", instance_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if start_time is not None: - _params["startTime"] = _SERIALIZER.query("start_time", start_time, "str") - if end_time is not None: - _params["endTime"] = _SERIALIZER.query("end_time", end_time, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class RestorableTablesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`restorable_tables` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, - location: str, - instance_id: str, - start_time: Optional[str] = None, - end_time: Optional[str] = None, - **kwargs: Any - ) -> Iterable["_models.RestorableTableGetResult"]: - """Show the event feed of all mutations done on all the Azure Cosmos DB Tables. This helps in - scenario where table was accidentally deleted. This API requires - 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. - - :param location: Cosmos DB region, with spaces between words and each word capitalized. - Required. - :type location: str - :param instance_id: The instanceId GUID of a restorable database account. Required. - :type instance_id: str - :param start_time: Restorable Tables event feed start time. Default value is None. - :type start_time: str - :param end_time: Restorable Tables event feed end time. Default value is None. - :type end_time: str - :return: An iterator like instance of either RestorableTableGetResult or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.RestorableTableGetResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.RestorableTablesListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - location=location, - instance_id=instance_id, - subscription_id=self._config.subscription_id, - start_time=start_time, - end_time=end_time, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("RestorableTablesListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request( + location: str, + instance_id: str, + subscription_id: str, + *, + start_time: Optional[str] = None, + end_time: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{instanceId}/restorableTables", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "location": _SERIALIZER.url("location", location, "str"), + "instanceId": _SERIALIZER.url("instance_id", instance_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if start_time is not None: + _params["startTime"] = _SERIALIZER.query("start_time", start_time, "str") + if end_time is not None: + _params["endTime"] = _SERIALIZER.query("end_time", end_time, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RestorableTablesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`restorable_tables` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, + location: str, + instance_id: str, + start_time: Optional[str] = None, + end_time: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.RestorableTableGetResult"]: + """Show the event feed of all mutations done on all the Azure Cosmos DB Tables. This helps in + scenario where table was accidentally deleted. This API requires + 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' permission. + + :param location: Cosmos DB region, with spaces between words and each word capitalized. + Required. + :type location: str + :param instance_id: The instanceId GUID of a restorable database account. Required. + :type instance_id: str + :param start_time: Restorable Tables event feed start time. Default value is None. + :type start_time: str + :param end_time: Restorable Tables event feed end time. Default value is None. + :type end_time: str + :return: An iterator like instance of either RestorableTableGetResult or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.RestorableTableGetResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RestorableTablesListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + location=location, + instance_id=instance_id, + subscription_id=self._config.subscription_id, + start_time=start_time, + end_time=end_time, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RestorableTablesListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_service_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_service_operations.py index fea4d147eae..826569589fe 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_service_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_service_operations.py @@ -1,671 +1,671 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.arm_polling import ARMPolling - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_request(resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/services", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_request( - resource_group_name: str, account_name: str, service_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/services/{serviceName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "serviceName": _SERIALIZER.url("service_name", service_name, "str", max_length=50, min_length=3), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request( - resource_group_name: str, account_name: str, service_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/services/{serviceName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "serviceName": _SERIALIZER.url("service_name", service_name, "str", max_length=50, min_length=3), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - resource_group_name: str, account_name: str, service_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/services/{serviceName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "serviceName": _SERIALIZER.url("service_name", service_name, "str", max_length=50, min_length=3), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -class ServiceOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`service` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list(self, resource_group_name: str, account_name: str, **kwargs: Any) -> Iterable["_models.ServiceResource"]: - """Gets the status of service. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either ServiceResource or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.ServiceResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ServiceResourceListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("ServiceResourceListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - def _create_initial( - self, - resource_group_name: str, - account_name: str, - service_name: str, - create_update_parameters: Union[_models.ServiceResourceCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_parameters, (IOBase, bytes)): - _content = create_update_parameters - else: - _json = self._serialize.body(create_update_parameters, "ServiceResourceCreateUpdateParameters") - - _request = build_create_request( - resource_group_name=resource_group_name, - account_name=account_name, - service_name=service_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create( - self, - resource_group_name: str, - account_name: str, - service_name: str, - create_update_parameters: _models.ServiceResourceCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ServiceResource]: - """Creates a service. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param service_name: Cosmos DB service name. Required. - :type service_name: str - :param create_update_parameters: The Service resource parameters. Required. - :type create_update_parameters: - ~azure.mgmt.cosmosdb.models.ServiceResourceCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ServiceResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ServiceResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create( - self, - resource_group_name: str, - account_name: str, - service_name: str, - create_update_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ServiceResource]: - """Creates a service. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param service_name: Cosmos DB service name. Required. - :type service_name: str - :param create_update_parameters: The Service resource parameters. Required. - :type create_update_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ServiceResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ServiceResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create( - self, - resource_group_name: str, - account_name: str, - service_name: str, - create_update_parameters: Union[_models.ServiceResourceCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.ServiceResource]: - """Creates a service. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param service_name: Cosmos DB service name. Required. - :type service_name: str - :param create_update_parameters: The Service resource parameters. Is either a - ServiceResourceCreateUpdateParameters type or a IO[bytes] type. Required. - :type create_update_parameters: - ~azure.mgmt.cosmosdb.models.ServiceResourceCreateUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either ServiceResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ServiceResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ServiceResource] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_initial( - resource_group_name=resource_group_name, - account_name=account_name, - service_name=service_name, - create_update_parameters=create_update_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ServiceResource", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ServiceResource].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ServiceResource]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @distributed_trace - def get( - self, resource_group_name: str, account_name: str, service_name: str, **kwargs: Any - ) -> _models.ServiceResource: - """Gets the status of service. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param service_name: Cosmos DB service name. Required. - :type service_name: str - :return: ServiceResource or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ServiceResource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ServiceResource] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - account_name=account_name, - service_name=service_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ServiceResource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _delete_initial( - self, resource_group_name: str, account_name: str, service_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - account_name=account_name, - service_name=service_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202, 204]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete( - self, resource_group_name: str, account_name: str, service_name: str, **kwargs: Any - ) -> LROPoller[None]: - """Deletes service with the given serviceName. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param service_name: Cosmos DB service name. Required. - :type service_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_initial( - resource_group_name=resource_group_name, - account_name=account_name, - service_name=service_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/services", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_request( + resource_group_name: str, account_name: str, service_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/services/{serviceName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "serviceName": _SERIALIZER.url("service_name", service_name, "str", max_length=50, min_length=3), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request( + resource_group_name: str, account_name: str, service_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/services/{serviceName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "serviceName": _SERIALIZER.url("service_name", service_name, "str", max_length=50, min_length=3), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, account_name: str, service_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/services/{serviceName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "serviceName": _SERIALIZER.url("service_name", service_name, "str", max_length=50, min_length=3), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +class ServiceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`service` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, resource_group_name: str, account_name: str, **kwargs: Any) -> Iterable["_models.ServiceResource"]: + """Gets the status of service. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either ServiceResource or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.ServiceResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ServiceResourceListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ServiceResourceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + def _create_initial( + self, + resource_group_name: str, + account_name: str, + service_name: str, + create_update_parameters: Union[_models.ServiceResourceCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_parameters, (IOBase, bytes)): + _content = create_update_parameters + else: + _json = self._serialize.body(create_update_parameters, "ServiceResourceCreateUpdateParameters") + + _request = build_create_request( + resource_group_name=resource_group_name, + account_name=account_name, + service_name=service_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create( + self, + resource_group_name: str, + account_name: str, + service_name: str, + create_update_parameters: _models.ServiceResourceCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ServiceResource]: + """Creates a service. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param service_name: Cosmos DB service name. Required. + :type service_name: str + :param create_update_parameters: The Service resource parameters. Required. + :type create_update_parameters: + ~azure.mgmt.cosmosdb.models.ServiceResourceCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ServiceResource or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ServiceResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create( + self, + resource_group_name: str, + account_name: str, + service_name: str, + create_update_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ServiceResource]: + """Creates a service. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param service_name: Cosmos DB service name. Required. + :type service_name: str + :param create_update_parameters: The Service resource parameters. Required. + :type create_update_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ServiceResource or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ServiceResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create( + self, + resource_group_name: str, + account_name: str, + service_name: str, + create_update_parameters: Union[_models.ServiceResourceCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.ServiceResource]: + """Creates a service. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param service_name: Cosmos DB service name. Required. + :type service_name: str + :param create_update_parameters: The Service resource parameters. Is either a + ServiceResourceCreateUpdateParameters type or a IO[bytes] type. Required. + :type create_update_parameters: + ~azure.mgmt.cosmosdb.models.ServiceResourceCreateUpdateParameters or IO[bytes] + :return: An instance of LROPoller that returns either ServiceResource or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ServiceResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ServiceResource] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_initial( + resource_group_name=resource_group_name, + account_name=account_name, + service_name=service_name, + create_update_parameters=create_update_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ServiceResource", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ServiceResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ServiceResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def get( + self, resource_group_name: str, account_name: str, service_name: str, **kwargs: Any + ) -> _models.ServiceResource: + """Gets the status of service. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param service_name: Cosmos DB service name. Required. + :type service_name: str + :return: ServiceResource or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ServiceResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ServiceResource] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + account_name=account_name, + service_name=service_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ServiceResource", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _delete_initial( + self, resource_group_name: str, account_name: str, service_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + account_name=account_name, + service_name=service_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete( + self, resource_group_name: str, account_name: str, service_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Deletes service with the given serviceName. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param service_name: Cosmos DB service name. Required. + :type service_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + account_name=account_name, + service_name=service_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_sql_resources_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_sql_resources_operations.py index 16a6adf6851..6e961b3a5a8 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_sql_resources_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_sql_resources_operations.py @@ -1,8460 +1,8460 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.arm_polling import ARMPolling - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_sql_databases_request( - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_sql_database_request( - resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_update_sql_database_request( - resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_sql_database_request( - resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) - - -def build_get_sql_database_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/throughputSettings/default", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_update_sql_database_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/throughputSettings/default", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_migrate_sql_database_to_autoscale_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/throughputSettings/default/migrateToAutoscale", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_migrate_sql_database_to_manual_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/throughputSettings/default/migrateToManualThroughput", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_client_encryption_keys_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/clientEncryptionKeys", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_client_encryption_key_request( - resource_group_name: str, - account_name: str, - database_name: str, - client_encryption_key_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/clientEncryptionKeys/{clientEncryptionKeyName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "clientEncryptionKeyName": _SERIALIZER.url("client_encryption_key_name", client_encryption_key_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_update_client_encryption_key_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - database_name: str, - client_encryption_key_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/clientEncryptionKeys/{clientEncryptionKeyName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "clientEncryptionKeyName": _SERIALIZER.url("client_encryption_key_name", client_encryption_key_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_sql_containers_request( - resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_sql_container_request( - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "containerName": _SERIALIZER.url("container_name", container_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_update_sql_container_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "containerName": _SERIALIZER.url("container_name", container_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_sql_container_request( - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "containerName": _SERIALIZER.url("container_name", container_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) - - -def build_sql_database_partition_merge_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/partitionMerge", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_sql_container_partition_merge_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/partitionMerge", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "containerName": _SERIALIZER.url("container_name", container_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_sql_container_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/throughputSettings/default", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "containerName": _SERIALIZER.url("container_name", container_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_update_sql_container_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/throughputSettings/default", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "containerName": _SERIALIZER.url("container_name", container_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_migrate_sql_container_to_autoscale_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/throughputSettings/default/migrateToAutoscale", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "containerName": _SERIALIZER.url("container_name", container_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_migrate_sql_container_to_manual_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/throughputSettings/default/migrateToManualThroughput", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "containerName": _SERIALIZER.url("container_name", container_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_sql_database_retrieve_throughput_distribution_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/throughputSettings/default/retrieveThroughputDistribution", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_sql_database_redistribute_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/throughputSettings/default/redistributeThroughput", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_sql_container_retrieve_throughput_distribution_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/throughputSettings/default/retrieveThroughputDistribution", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "containerName": _SERIALIZER.url("container_name", container_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_sql_container_redistribute_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/throughputSettings/default/redistributeThroughput", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "containerName": _SERIALIZER.url("container_name", container_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_sql_stored_procedures_request( - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/storedProcedures", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "containerName": _SERIALIZER.url("container_name", container_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_sql_stored_procedure_request( - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - stored_procedure_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/storedProcedures/{storedProcedureName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "containerName": _SERIALIZER.url("container_name", container_name, "str"), - "storedProcedureName": _SERIALIZER.url("stored_procedure_name", stored_procedure_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_update_sql_stored_procedure_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - stored_procedure_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/storedProcedures/{storedProcedureName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "containerName": _SERIALIZER.url("container_name", container_name, "str"), - "storedProcedureName": _SERIALIZER.url("stored_procedure_name", stored_procedure_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_sql_stored_procedure_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - stored_procedure_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/storedProcedures/{storedProcedureName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "containerName": _SERIALIZER.url("container_name", container_name, "str"), - "storedProcedureName": _SERIALIZER.url("stored_procedure_name", stored_procedure_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) - - -def build_list_sql_user_defined_functions_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/userDefinedFunctions", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "containerName": _SERIALIZER.url("container_name", container_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_sql_user_defined_function_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - user_defined_function_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/userDefinedFunctions/{userDefinedFunctionName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "containerName": _SERIALIZER.url("container_name", container_name, "str"), - "userDefinedFunctionName": _SERIALIZER.url("user_defined_function_name", user_defined_function_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_update_sql_user_defined_function_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - user_defined_function_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/userDefinedFunctions/{userDefinedFunctionName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "containerName": _SERIALIZER.url("container_name", container_name, "str"), - "userDefinedFunctionName": _SERIALIZER.url("user_defined_function_name", user_defined_function_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_sql_user_defined_function_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - user_defined_function_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/userDefinedFunctions/{userDefinedFunctionName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "containerName": _SERIALIZER.url("container_name", container_name, "str"), - "userDefinedFunctionName": _SERIALIZER.url("user_defined_function_name", user_defined_function_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) - - -def build_list_sql_triggers_request( - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/triggers", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "containerName": _SERIALIZER.url("container_name", container_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_sql_trigger_request( - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - trigger_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/triggers/{triggerName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "containerName": _SERIALIZER.url("container_name", container_name, "str"), - "triggerName": _SERIALIZER.url("trigger_name", trigger_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_update_sql_trigger_request( - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - trigger_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/triggers/{triggerName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "containerName": _SERIALIZER.url("container_name", container_name, "str"), - "triggerName": _SERIALIZER.url("trigger_name", trigger_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_sql_trigger_request( - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - trigger_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/triggers/{triggerName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "containerName": _SERIALIZER.url("container_name", container_name, "str"), - "triggerName": _SERIALIZER.url("trigger_name", trigger_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) - - -def build_get_sql_role_definition_request( - role_definition_id: str, resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlRoleDefinitions/{roleDefinitionId}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "roleDefinitionId": _SERIALIZER.url("role_definition_id", role_definition_id, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_update_sql_role_definition_request( # pylint: disable=name-too-long - role_definition_id: str, resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlRoleDefinitions/{roleDefinitionId}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "roleDefinitionId": _SERIALIZER.url("role_definition_id", role_definition_id, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_sql_role_definition_request( - role_definition_id: str, resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlRoleDefinitions/{roleDefinitionId}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "roleDefinitionId": _SERIALIZER.url("role_definition_id", role_definition_id, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_sql_role_definitions_request( - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlRoleDefinitions", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_sql_role_assignment_request( - role_assignment_id: str, resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlRoleAssignments/{roleAssignmentId}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "roleAssignmentId": _SERIALIZER.url("role_assignment_id", role_assignment_id, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_update_sql_role_assignment_request( # pylint: disable=name-too-long - role_assignment_id: str, resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlRoleAssignments/{roleAssignmentId}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "roleAssignmentId": _SERIALIZER.url("role_assignment_id", role_assignment_id, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_sql_role_assignment_request( - role_assignment_id: str, resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlRoleAssignments/{roleAssignmentId}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "roleAssignmentId": _SERIALIZER.url("role_assignment_id", role_assignment_id, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_sql_role_assignments_request( - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlRoleAssignments", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_retrieve_continuous_backup_information_request( # pylint: disable=name-too-long - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/retrieveContinuousBackupInformation", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "databaseName": _SERIALIZER.url("database_name", database_name, "str"), - "containerName": _SERIALIZER.url("container_name", container_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -class SqlResourcesOperations: # pylint: disable=too-many-public-methods - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`sql_resources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_sql_databases( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> Iterable["_models.SqlDatabaseGetResults"]: - """Lists the SQL databases under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either SqlDatabaseGetResults or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.SqlDatabaseGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SqlDatabaseListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_sql_databases_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("SqlDatabaseListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get_sql_database( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> _models.SqlDatabaseGetResults: - """Gets the SQL database under an existing Azure Cosmos DB database account with the provided - name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: SqlDatabaseGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.SqlDatabaseGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SqlDatabaseGetResults] = kwargs.pop("cls", None) - - _request = build_get_sql_database_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("SqlDatabaseGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _create_update_sql_database_initial( - self, - resource_group_name: str, - account_name: str, - database_name: str, - create_update_sql_database_parameters: Union[_models.SqlDatabaseCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_sql_database_parameters, (IOBase, bytes)): - _content = create_update_sql_database_parameters - else: - _json = self._serialize.body(create_update_sql_database_parameters, "SqlDatabaseCreateUpdateParameters") - - _request = build_create_update_sql_database_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_update_sql_database( - self, - resource_group_name: str, - account_name: str, - database_name: str, - create_update_sql_database_parameters: _models.SqlDatabaseCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.SqlDatabaseGetResults]: - """Create or update an Azure Cosmos DB SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param create_update_sql_database_parameters: The parameters to provide for the current SQL - database. Required. - :type create_update_sql_database_parameters: - ~azure.mgmt.cosmosdb.models.SqlDatabaseCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either SqlDatabaseGetResults or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlDatabaseGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_update_sql_database( - self, - resource_group_name: str, - account_name: str, - database_name: str, - create_update_sql_database_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.SqlDatabaseGetResults]: - """Create or update an Azure Cosmos DB SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param create_update_sql_database_parameters: The parameters to provide for the current SQL - database. Required. - :type create_update_sql_database_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either SqlDatabaseGetResults or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlDatabaseGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_update_sql_database( - self, - resource_group_name: str, - account_name: str, - database_name: str, - create_update_sql_database_parameters: Union[_models.SqlDatabaseCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.SqlDatabaseGetResults]: - """Create or update an Azure Cosmos DB SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param create_update_sql_database_parameters: The parameters to provide for the current SQL - database. Is either a SqlDatabaseCreateUpdateParameters type or a IO[bytes] type. Required. - :type create_update_sql_database_parameters: - ~azure.mgmt.cosmosdb.models.SqlDatabaseCreateUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either SqlDatabaseGetResults or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlDatabaseGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SqlDatabaseGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_update_sql_database_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - create_update_sql_database_parameters=create_update_sql_database_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("SqlDatabaseGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.SqlDatabaseGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.SqlDatabaseGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _delete_sql_database_initial( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_sql_database_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete_sql_database( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> LROPoller[None]: - """Deletes an existing Azure Cosmos DB SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_sql_database_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace - def get_sql_database_throughput( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> _models.ThroughputSettingsGetResults: - """Gets the RUs per second of the SQL database under an existing Azure Cosmos DB database account - with the provided name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: ThroughputSettingsGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - - _request = build_get_sql_database_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _update_sql_database_throughput_initial( - self, - resource_group_name: str, - account_name: str, - database_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(update_throughput_parameters, (IOBase, bytes)): - _content = update_throughput_parameters - else: - _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") - - _request = build_update_sql_database_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_update_sql_database_throughput( - self, - resource_group_name: str, - account_name: str, - database_name: str, - update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param update_throughput_parameters: The parameters to provide for the RUs per second of the - current SQL database. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_update_sql_database_throughput( - self, - resource_group_name: str, - account_name: str, - database_name: str, - update_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param update_throughput_parameters: The parameters to provide for the RUs per second of the - current SQL database. Required. - :type update_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_update_sql_database_throughput( - self, - resource_group_name: str, - account_name: str, - database_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param update_throughput_parameters: The parameters to provide for the RUs per second of the - current SQL database. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] type. - Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._update_sql_database_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - update_throughput_parameters=update_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _migrate_sql_database_to_autoscale_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_sql_database_to_autoscale_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_migrate_sql_database_to_autoscale( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB SQL database from manual throughput to autoscale. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._migrate_sql_database_to_autoscale_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _migrate_sql_database_to_manual_throughput_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_sql_database_to_manual_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_migrate_sql_database_to_manual_throughput( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB SQL database from autoscale to manual throughput. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._migrate_sql_database_to_manual_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @distributed_trace - def list_client_encryption_keys( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> Iterable["_models.ClientEncryptionKeyGetResults"]: - """Lists the ClientEncryptionKeys under an existing Azure Cosmos DB SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: An iterator like instance of either ClientEncryptionKeyGetResults or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.ClientEncryptionKeyGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ClientEncryptionKeysListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_client_encryption_keys_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("ClientEncryptionKeysListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get_client_encryption_key( - self, - resource_group_name: str, - account_name: str, - database_name: str, - client_encryption_key_name: str, - **kwargs: Any - ) -> _models.ClientEncryptionKeyGetResults: - """Gets the ClientEncryptionKey under an existing Azure Cosmos DB SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param client_encryption_key_name: Cosmos DB ClientEncryptionKey name. Required. - :type client_encryption_key_name: str - :return: ClientEncryptionKeyGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ClientEncryptionKeyGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ClientEncryptionKeyGetResults] = kwargs.pop("cls", None) - - _request = build_get_client_encryption_key_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - client_encryption_key_name=client_encryption_key_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ClientEncryptionKeyGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _create_update_client_encryption_key_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - client_encryption_key_name: str, - create_update_client_encryption_key_parameters: Union[ - _models.ClientEncryptionKeyCreateUpdateParameters, IO[bytes] - ], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_client_encryption_key_parameters, (IOBase, bytes)): - _content = create_update_client_encryption_key_parameters - else: - _json = self._serialize.body( - create_update_client_encryption_key_parameters, "ClientEncryptionKeyCreateUpdateParameters" - ) - - _request = build_create_update_client_encryption_key_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - client_encryption_key_name=client_encryption_key_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_update_client_encryption_key( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - client_encryption_key_name: str, - create_update_client_encryption_key_parameters: _models.ClientEncryptionKeyCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ClientEncryptionKeyGetResults]: - """Create or update a ClientEncryptionKey. This API is meant to be invoked via tools such as the - Azure Powershell (instead of directly). - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param client_encryption_key_name: Cosmos DB ClientEncryptionKey name. Required. - :type client_encryption_key_name: str - :param create_update_client_encryption_key_parameters: The parameters to provide for the client - encryption key. Required. - :type create_update_client_encryption_key_parameters: - ~azure.mgmt.cosmosdb.models.ClientEncryptionKeyCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ClientEncryptionKeyGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ClientEncryptionKeyGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_update_client_encryption_key( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - client_encryption_key_name: str, - create_update_client_encryption_key_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ClientEncryptionKeyGetResults]: - """Create or update a ClientEncryptionKey. This API is meant to be invoked via tools such as the - Azure Powershell (instead of directly). - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param client_encryption_key_name: Cosmos DB ClientEncryptionKey name. Required. - :type client_encryption_key_name: str - :param create_update_client_encryption_key_parameters: The parameters to provide for the client - encryption key. Required. - :type create_update_client_encryption_key_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ClientEncryptionKeyGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ClientEncryptionKeyGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_update_client_encryption_key( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - client_encryption_key_name: str, - create_update_client_encryption_key_parameters: Union[ - _models.ClientEncryptionKeyCreateUpdateParameters, IO[bytes] - ], - **kwargs: Any - ) -> LROPoller[_models.ClientEncryptionKeyGetResults]: - """Create or update a ClientEncryptionKey. This API is meant to be invoked via tools such as the - Azure Powershell (instead of directly). - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param client_encryption_key_name: Cosmos DB ClientEncryptionKey name. Required. - :type client_encryption_key_name: str - :param create_update_client_encryption_key_parameters: The parameters to provide for the client - encryption key. Is either a ClientEncryptionKeyCreateUpdateParameters type or a IO[bytes] type. - Required. - :type create_update_client_encryption_key_parameters: - ~azure.mgmt.cosmosdb.models.ClientEncryptionKeyCreateUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either ClientEncryptionKeyGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ClientEncryptionKeyGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ClientEncryptionKeyGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_update_client_encryption_key_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - client_encryption_key_name=client_encryption_key_name, - create_update_client_encryption_key_parameters=create_update_client_encryption_key_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ClientEncryptionKeyGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ClientEncryptionKeyGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ClientEncryptionKeyGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @distributed_trace - def list_sql_containers( - self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any - ) -> Iterable["_models.SqlContainerGetResults"]: - """Lists the SQL container under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :return: An iterator like instance of either SqlContainerGetResults or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.SqlContainerGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SqlContainerListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_sql_containers_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("SqlContainerListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get_sql_container( - self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any - ) -> _models.SqlContainerGetResults: - """Gets the SQL container under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :return: SqlContainerGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.SqlContainerGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SqlContainerGetResults] = kwargs.pop("cls", None) - - _request = build_get_sql_container_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("SqlContainerGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _create_update_sql_container_initial( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - create_update_sql_container_parameters: Union[_models.SqlContainerCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_sql_container_parameters, (IOBase, bytes)): - _content = create_update_sql_container_parameters - else: - _json = self._serialize.body(create_update_sql_container_parameters, "SqlContainerCreateUpdateParameters") - - _request = build_create_update_sql_container_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_update_sql_container( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - create_update_sql_container_parameters: _models.SqlContainerCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.SqlContainerGetResults]: - """Create or update an Azure Cosmos DB SQL container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param create_update_sql_container_parameters: The parameters to provide for the current SQL - container. Required. - :type create_update_sql_container_parameters: - ~azure.mgmt.cosmosdb.models.SqlContainerCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either SqlContainerGetResults or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlContainerGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_update_sql_container( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - create_update_sql_container_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.SqlContainerGetResults]: - """Create or update an Azure Cosmos DB SQL container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param create_update_sql_container_parameters: The parameters to provide for the current SQL - container. Required. - :type create_update_sql_container_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either SqlContainerGetResults or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlContainerGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_update_sql_container( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - create_update_sql_container_parameters: Union[_models.SqlContainerCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.SqlContainerGetResults]: - """Create or update an Azure Cosmos DB SQL container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param create_update_sql_container_parameters: The parameters to provide for the current SQL - container. Is either a SqlContainerCreateUpdateParameters type or a IO[bytes] type. Required. - :type create_update_sql_container_parameters: - ~azure.mgmt.cosmosdb.models.SqlContainerCreateUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either SqlContainerGetResults or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlContainerGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SqlContainerGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_update_sql_container_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - create_update_sql_container_parameters=create_update_sql_container_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("SqlContainerGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.SqlContainerGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.SqlContainerGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _delete_sql_container_initial( - self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_sql_container_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete_sql_container( - self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any - ) -> LROPoller[None]: - """Deletes an existing Azure Cosmos DB SQL container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_sql_container_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - def _sql_database_partition_merge_initial( - self, - resource_group_name: str, - account_name: str, - database_name: str, - merge_parameters: Union[_models.MergeParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(merge_parameters, (IOBase, bytes)): - _content = merge_parameters - else: - _json = self._serialize.body(merge_parameters, "MergeParameters") - - _request = build_sql_database_partition_merge_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_sql_database_partition_merge( - self, - resource_group_name: str, - account_name: str, - database_name: str, - merge_parameters: _models.MergeParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionStorageInfoCollection]: - """Merges the partitions of a SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param merge_parameters: The parameters for the merge operation. Required. - :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either PhysicalPartitionStorageInfoCollection or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_sql_database_partition_merge( - self, - resource_group_name: str, - account_name: str, - database_name: str, - merge_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionStorageInfoCollection]: - """Merges the partitions of a SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param merge_parameters: The parameters for the merge operation. Required. - :type merge_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either PhysicalPartitionStorageInfoCollection or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_sql_database_partition_merge( - self, - resource_group_name: str, - account_name: str, - database_name: str, - merge_parameters: Union[_models.MergeParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionStorageInfoCollection]: - """Merges the partitions of a SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param merge_parameters: The parameters for the merge operation. Is either a MergeParameters - type or a IO[bytes] type. Required. - :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters or IO[bytes] - :return: An instance of LROPoller that returns either PhysicalPartitionStorageInfoCollection or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PhysicalPartitionStorageInfoCollection] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._sql_database_partition_merge_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - merge_parameters=merge_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("PhysicalPartitionStorageInfoCollection", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.PhysicalPartitionStorageInfoCollection].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.PhysicalPartitionStorageInfoCollection]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _list_sql_container_partition_merge_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - merge_parameters: Union[_models.MergeParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(merge_parameters, (IOBase, bytes)): - _content = merge_parameters - else: - _json = self._serialize.body(merge_parameters, "MergeParameters") - - _request = build_list_sql_container_partition_merge_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_list_sql_container_partition_merge( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - merge_parameters: _models.MergeParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionStorageInfoCollection]: - """Merges the partitions of a SQL Container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param merge_parameters: The parameters for the merge operation. Required. - :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either PhysicalPartitionStorageInfoCollection or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_list_sql_container_partition_merge( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - merge_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionStorageInfoCollection]: - """Merges the partitions of a SQL Container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param merge_parameters: The parameters for the merge operation. Required. - :type merge_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either PhysicalPartitionStorageInfoCollection or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_list_sql_container_partition_merge( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - merge_parameters: Union[_models.MergeParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionStorageInfoCollection]: - """Merges the partitions of a SQL Container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param merge_parameters: The parameters for the merge operation. Is either a MergeParameters - type or a IO[bytes] type. Required. - :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters or IO[bytes] - :return: An instance of LROPoller that returns either PhysicalPartitionStorageInfoCollection or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PhysicalPartitionStorageInfoCollection] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._list_sql_container_partition_merge_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - merge_parameters=merge_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("PhysicalPartitionStorageInfoCollection", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.PhysicalPartitionStorageInfoCollection].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.PhysicalPartitionStorageInfoCollection]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @distributed_trace - def get_sql_container_throughput( - self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any - ) -> _models.ThroughputSettingsGetResults: - """Gets the RUs per second of the SQL container under an existing Azure Cosmos DB database - account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :return: ThroughputSettingsGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - - _request = build_get_sql_container_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _update_sql_container_throughput_initial( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(update_throughput_parameters, (IOBase, bytes)): - _content = update_throughput_parameters - else: - _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") - - _request = build_update_sql_container_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_update_sql_container_throughput( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB SQL container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param update_throughput_parameters: The parameters to provide for the RUs per second of the - current SQL container. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_update_sql_container_throughput( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - update_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB SQL container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param update_throughput_parameters: The parameters to provide for the RUs per second of the - current SQL container. Required. - :type update_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_update_sql_container_throughput( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB SQL container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param update_throughput_parameters: The parameters to provide for the RUs per second of the - current SQL container. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] type. - Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._update_sql_container_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - update_throughput_parameters=update_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _migrate_sql_container_to_autoscale_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_sql_container_to_autoscale_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_migrate_sql_container_to_autoscale( - self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB SQL container from manual throughput to autoscale. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._migrate_sql_container_to_autoscale_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _migrate_sql_container_to_manual_throughput_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_sql_container_to_manual_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_migrate_sql_container_to_manual_throughput( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB SQL container from autoscale to manual throughput. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._migrate_sql_container_to_manual_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _sql_database_retrieve_throughput_distribution_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(retrieve_throughput_parameters, (IOBase, bytes)): - _content = retrieve_throughput_parameters - else: - _json = self._serialize.body(retrieve_throughput_parameters, "RetrieveThroughputParameters") - - _request = build_sql_database_retrieve_throughput_distribution_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_sql_database_retrieve_throughput_distribution( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - retrieve_throughput_parameters: _models.RetrieveThroughputParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Retrieve throughput distribution for an Azure Cosmos DB SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput - distribution for the current SQL database. Required. - :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_sql_database_retrieve_throughput_distribution( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - retrieve_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Retrieve throughput distribution for an Azure Cosmos DB SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput - distribution for the current SQL database. Required. - :type retrieve_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_sql_database_retrieve_throughput_distribution( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Retrieve throughput distribution for an Azure Cosmos DB SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput - distribution for the current SQL database. Is either a RetrieveThroughputParameters type or a - IO[bytes] type. Required. - :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters - or IO[bytes] - :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._sql_database_retrieve_throughput_distribution_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - retrieve_throughput_parameters=retrieve_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.PhysicalPartitionThroughputInfoResult]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _sql_database_redistribute_throughput_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(redistribute_throughput_parameters, (IOBase, bytes)): - _content = redistribute_throughput_parameters - else: - _json = self._serialize.body(redistribute_throughput_parameters, "RedistributeThroughputParameters") - - _request = build_sql_database_redistribute_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_sql_database_redistribute_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - redistribute_throughput_parameters: _models.RedistributeThroughputParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Redistribute throughput for an Azure Cosmos DB SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param redistribute_throughput_parameters: The parameters to provide for redistributing - throughput for the current SQL database. Required. - :type redistribute_throughput_parameters: - ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_sql_database_redistribute_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - redistribute_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Redistribute throughput for an Azure Cosmos DB SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param redistribute_throughput_parameters: The parameters to provide for redistributing - throughput for the current SQL database. Required. - :type redistribute_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_sql_database_redistribute_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Redistribute throughput for an Azure Cosmos DB SQL database. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param redistribute_throughput_parameters: The parameters to provide for redistributing - throughput for the current SQL database. Is either a RedistributeThroughputParameters type or a - IO[bytes] type. Required. - :type redistribute_throughput_parameters: - ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters or IO[bytes] - :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._sql_database_redistribute_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - redistribute_throughput_parameters=redistribute_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.PhysicalPartitionThroughputInfoResult]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _sql_container_retrieve_throughput_distribution_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(retrieve_throughput_parameters, (IOBase, bytes)): - _content = retrieve_throughput_parameters - else: - _json = self._serialize.body(retrieve_throughput_parameters, "RetrieveThroughputParameters") - - _request = build_sql_container_retrieve_throughput_distribution_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_sql_container_retrieve_throughput_distribution( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - retrieve_throughput_parameters: _models.RetrieveThroughputParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Retrieve throughput distribution for an Azure Cosmos DB SQL container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput - distribution for the current SQL container. Required. - :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_sql_container_retrieve_throughput_distribution( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - retrieve_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Retrieve throughput distribution for an Azure Cosmos DB SQL container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput - distribution for the current SQL container. Required. - :type retrieve_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_sql_container_retrieve_throughput_distribution( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Retrieve throughput distribution for an Azure Cosmos DB SQL container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput - distribution for the current SQL container. Is either a RetrieveThroughputParameters type or a - IO[bytes] type. Required. - :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters - or IO[bytes] - :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._sql_container_retrieve_throughput_distribution_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - retrieve_throughput_parameters=retrieve_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.PhysicalPartitionThroughputInfoResult]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _sql_container_redistribute_throughput_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(redistribute_throughput_parameters, (IOBase, bytes)): - _content = redistribute_throughput_parameters - else: - _json = self._serialize.body(redistribute_throughput_parameters, "RedistributeThroughputParameters") - - _request = build_sql_container_redistribute_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_sql_container_redistribute_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - redistribute_throughput_parameters: _models.RedistributeThroughputParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Redistribute throughput for an Azure Cosmos DB SQL container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param redistribute_throughput_parameters: The parameters to provide for redistributing - throughput for the current SQL container. Required. - :type redistribute_throughput_parameters: - ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_sql_container_redistribute_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - redistribute_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Redistribute throughput for an Azure Cosmos DB SQL container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param redistribute_throughput_parameters: The parameters to provide for redistributing - throughput for the current SQL container. Required. - :type redistribute_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_sql_container_redistribute_throughput( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: - """Redistribute throughput for an Azure Cosmos DB SQL container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param redistribute_throughput_parameters: The parameters to provide for redistributing - throughput for the current SQL container. Is either a RedistributeThroughputParameters type or - a IO[bytes] type. Required. - :type redistribute_throughput_parameters: - ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters or IO[bytes] - :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or - the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._sql_container_redistribute_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - redistribute_throughput_parameters=redistribute_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.PhysicalPartitionThroughputInfoResult]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @distributed_trace - def list_sql_stored_procedures( - self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any - ) -> Iterable["_models.SqlStoredProcedureGetResults"]: - """Lists the SQL storedProcedure under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :return: An iterator like instance of either SqlStoredProcedureGetResults or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.SqlStoredProcedureGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SqlStoredProcedureListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_sql_stored_procedures_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("SqlStoredProcedureListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get_sql_stored_procedure( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - stored_procedure_name: str, - **kwargs: Any - ) -> _models.SqlStoredProcedureGetResults: - """Gets the SQL storedProcedure under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param stored_procedure_name: Cosmos DB storedProcedure name. Required. - :type stored_procedure_name: str - :return: SqlStoredProcedureGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.SqlStoredProcedureGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SqlStoredProcedureGetResults] = kwargs.pop("cls", None) - - _request = build_get_sql_stored_procedure_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - stored_procedure_name=stored_procedure_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("SqlStoredProcedureGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _create_update_sql_stored_procedure_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - stored_procedure_name: str, - create_update_sql_stored_procedure_parameters: Union[ - _models.SqlStoredProcedureCreateUpdateParameters, IO[bytes] - ], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_sql_stored_procedure_parameters, (IOBase, bytes)): - _content = create_update_sql_stored_procedure_parameters - else: - _json = self._serialize.body( - create_update_sql_stored_procedure_parameters, "SqlStoredProcedureCreateUpdateParameters" - ) - - _request = build_create_update_sql_stored_procedure_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - stored_procedure_name=stored_procedure_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_update_sql_stored_procedure( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - stored_procedure_name: str, - create_update_sql_stored_procedure_parameters: _models.SqlStoredProcedureCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.SqlStoredProcedureGetResults]: - """Create or update an Azure Cosmos DB SQL storedProcedure. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param stored_procedure_name: Cosmos DB storedProcedure name. Required. - :type stored_procedure_name: str - :param create_update_sql_stored_procedure_parameters: The parameters to provide for the current - SQL storedProcedure. Required. - :type create_update_sql_stored_procedure_parameters: - ~azure.mgmt.cosmosdb.models.SqlStoredProcedureCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either SqlStoredProcedureGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlStoredProcedureGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_update_sql_stored_procedure( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - stored_procedure_name: str, - create_update_sql_stored_procedure_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.SqlStoredProcedureGetResults]: - """Create or update an Azure Cosmos DB SQL storedProcedure. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param stored_procedure_name: Cosmos DB storedProcedure name. Required. - :type stored_procedure_name: str - :param create_update_sql_stored_procedure_parameters: The parameters to provide for the current - SQL storedProcedure. Required. - :type create_update_sql_stored_procedure_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either SqlStoredProcedureGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlStoredProcedureGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_update_sql_stored_procedure( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - stored_procedure_name: str, - create_update_sql_stored_procedure_parameters: Union[ - _models.SqlStoredProcedureCreateUpdateParameters, IO[bytes] - ], - **kwargs: Any - ) -> LROPoller[_models.SqlStoredProcedureGetResults]: - """Create or update an Azure Cosmos DB SQL storedProcedure. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param stored_procedure_name: Cosmos DB storedProcedure name. Required. - :type stored_procedure_name: str - :param create_update_sql_stored_procedure_parameters: The parameters to provide for the current - SQL storedProcedure. Is either a SqlStoredProcedureCreateUpdateParameters type or a IO[bytes] - type. Required. - :type create_update_sql_stored_procedure_parameters: - ~azure.mgmt.cosmosdb.models.SqlStoredProcedureCreateUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either SqlStoredProcedureGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlStoredProcedureGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SqlStoredProcedureGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_update_sql_stored_procedure_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - stored_procedure_name=stored_procedure_name, - create_update_sql_stored_procedure_parameters=create_update_sql_stored_procedure_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("SqlStoredProcedureGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.SqlStoredProcedureGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.SqlStoredProcedureGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _delete_sql_stored_procedure_initial( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - stored_procedure_name: str, - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_sql_stored_procedure_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - stored_procedure_name=stored_procedure_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete_sql_stored_procedure( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - stored_procedure_name: str, - **kwargs: Any - ) -> LROPoller[None]: - """Deletes an existing Azure Cosmos DB SQL storedProcedure. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param stored_procedure_name: Cosmos DB storedProcedure name. Required. - :type stored_procedure_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_sql_stored_procedure_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - stored_procedure_name=stored_procedure_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace - def list_sql_user_defined_functions( - self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any - ) -> Iterable["_models.SqlUserDefinedFunctionGetResults"]: - """Lists the SQL userDefinedFunction under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :return: An iterator like instance of either SqlUserDefinedFunctionGetResults or the result of - cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SqlUserDefinedFunctionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_sql_user_defined_functions_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("SqlUserDefinedFunctionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get_sql_user_defined_function( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - user_defined_function_name: str, - **kwargs: Any - ) -> _models.SqlUserDefinedFunctionGetResults: - """Gets the SQL userDefinedFunction under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param user_defined_function_name: Cosmos DB userDefinedFunction name. Required. - :type user_defined_function_name: str - :return: SqlUserDefinedFunctionGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SqlUserDefinedFunctionGetResults] = kwargs.pop("cls", None) - - _request = build_get_sql_user_defined_function_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - user_defined_function_name=user_defined_function_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("SqlUserDefinedFunctionGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _create_update_sql_user_defined_function_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - user_defined_function_name: str, - create_update_sql_user_defined_function_parameters: Union[ - _models.SqlUserDefinedFunctionCreateUpdateParameters, IO[bytes] - ], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_sql_user_defined_function_parameters, (IOBase, bytes)): - _content = create_update_sql_user_defined_function_parameters - else: - _json = self._serialize.body( - create_update_sql_user_defined_function_parameters, "SqlUserDefinedFunctionCreateUpdateParameters" - ) - - _request = build_create_update_sql_user_defined_function_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - user_defined_function_name=user_defined_function_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_update_sql_user_defined_function( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - user_defined_function_name: str, - create_update_sql_user_defined_function_parameters: _models.SqlUserDefinedFunctionCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.SqlUserDefinedFunctionGetResults]: - """Create or update an Azure Cosmos DB SQL userDefinedFunction. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param user_defined_function_name: Cosmos DB userDefinedFunction name. Required. - :type user_defined_function_name: str - :param create_update_sql_user_defined_function_parameters: The parameters to provide for the - current SQL userDefinedFunction. Required. - :type create_update_sql_user_defined_function_parameters: - ~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either SqlUserDefinedFunctionGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_update_sql_user_defined_function( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - user_defined_function_name: str, - create_update_sql_user_defined_function_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.SqlUserDefinedFunctionGetResults]: - """Create or update an Azure Cosmos DB SQL userDefinedFunction. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param user_defined_function_name: Cosmos DB userDefinedFunction name. Required. - :type user_defined_function_name: str - :param create_update_sql_user_defined_function_parameters: The parameters to provide for the - current SQL userDefinedFunction. Required. - :type create_update_sql_user_defined_function_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either SqlUserDefinedFunctionGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_update_sql_user_defined_function( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - user_defined_function_name: str, - create_update_sql_user_defined_function_parameters: Union[ - _models.SqlUserDefinedFunctionCreateUpdateParameters, IO[bytes] - ], - **kwargs: Any - ) -> LROPoller[_models.SqlUserDefinedFunctionGetResults]: - """Create or update an Azure Cosmos DB SQL userDefinedFunction. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param user_defined_function_name: Cosmos DB userDefinedFunction name. Required. - :type user_defined_function_name: str - :param create_update_sql_user_defined_function_parameters: The parameters to provide for the - current SQL userDefinedFunction. Is either a SqlUserDefinedFunctionCreateUpdateParameters type - or a IO[bytes] type. Required. - :type create_update_sql_user_defined_function_parameters: - ~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionCreateUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either SqlUserDefinedFunctionGetResults or the - result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SqlUserDefinedFunctionGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_update_sql_user_defined_function_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - user_defined_function_name=user_defined_function_name, - create_update_sql_user_defined_function_parameters=create_update_sql_user_defined_function_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("SqlUserDefinedFunctionGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.SqlUserDefinedFunctionGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.SqlUserDefinedFunctionGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _delete_sql_user_defined_function_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - user_defined_function_name: str, - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_sql_user_defined_function_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - user_defined_function_name=user_defined_function_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete_sql_user_defined_function( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - user_defined_function_name: str, - **kwargs: Any - ) -> LROPoller[None]: - """Deletes an existing Azure Cosmos DB SQL userDefinedFunction. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param user_defined_function_name: Cosmos DB userDefinedFunction name. Required. - :type user_defined_function_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_sql_user_defined_function_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - user_defined_function_name=user_defined_function_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace - def list_sql_triggers( - self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any - ) -> Iterable["_models.SqlTriggerGetResults"]: - """Lists the SQL trigger under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :return: An iterator like instance of either SqlTriggerGetResults or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.SqlTriggerGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SqlTriggerListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_sql_triggers_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("SqlTriggerListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get_sql_trigger( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - trigger_name: str, - **kwargs: Any - ) -> _models.SqlTriggerGetResults: - """Gets the SQL trigger under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param trigger_name: Cosmos DB trigger name. Required. - :type trigger_name: str - :return: SqlTriggerGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.SqlTriggerGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SqlTriggerGetResults] = kwargs.pop("cls", None) - - _request = build_get_sql_trigger_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - trigger_name=trigger_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("SqlTriggerGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _create_update_sql_trigger_initial( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - trigger_name: str, - create_update_sql_trigger_parameters: Union[_models.SqlTriggerCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_sql_trigger_parameters, (IOBase, bytes)): - _content = create_update_sql_trigger_parameters - else: - _json = self._serialize.body(create_update_sql_trigger_parameters, "SqlTriggerCreateUpdateParameters") - - _request = build_create_update_sql_trigger_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - trigger_name=trigger_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_update_sql_trigger( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - trigger_name: str, - create_update_sql_trigger_parameters: _models.SqlTriggerCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.SqlTriggerGetResults]: - """Create or update an Azure Cosmos DB SQL trigger. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param trigger_name: Cosmos DB trigger name. Required. - :type trigger_name: str - :param create_update_sql_trigger_parameters: The parameters to provide for the current SQL - trigger. Required. - :type create_update_sql_trigger_parameters: - ~azure.mgmt.cosmosdb.models.SqlTriggerCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either SqlTriggerGetResults or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlTriggerGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_update_sql_trigger( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - trigger_name: str, - create_update_sql_trigger_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.SqlTriggerGetResults]: - """Create or update an Azure Cosmos DB SQL trigger. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param trigger_name: Cosmos DB trigger name. Required. - :type trigger_name: str - :param create_update_sql_trigger_parameters: The parameters to provide for the current SQL - trigger. Required. - :type create_update_sql_trigger_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either SqlTriggerGetResults or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlTriggerGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_update_sql_trigger( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - trigger_name: str, - create_update_sql_trigger_parameters: Union[_models.SqlTriggerCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.SqlTriggerGetResults]: - """Create or update an Azure Cosmos DB SQL trigger. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param trigger_name: Cosmos DB trigger name. Required. - :type trigger_name: str - :param create_update_sql_trigger_parameters: The parameters to provide for the current SQL - trigger. Is either a SqlTriggerCreateUpdateParameters type or a IO[bytes] type. Required. - :type create_update_sql_trigger_parameters: - ~azure.mgmt.cosmosdb.models.SqlTriggerCreateUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either SqlTriggerGetResults or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlTriggerGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SqlTriggerGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_update_sql_trigger_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - trigger_name=trigger_name, - create_update_sql_trigger_parameters=create_update_sql_trigger_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("SqlTriggerGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.SqlTriggerGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.SqlTriggerGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _delete_sql_trigger_initial( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - trigger_name: str, - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_sql_trigger_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - trigger_name=trigger_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete_sql_trigger( - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - trigger_name: str, - **kwargs: Any - ) -> LROPoller[None]: - """Deletes an existing Azure Cosmos DB SQL trigger. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param trigger_name: Cosmos DB trigger name. Required. - :type trigger_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_sql_trigger_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - trigger_name=trigger_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace - def get_sql_role_definition( - self, role_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any - ) -> _models.SqlRoleDefinitionGetResults: - """Retrieves the properties of an existing Azure Cosmos DB SQL Role Definition with the given Id. - - :param role_definition_id: The GUID for the Role Definition. Required. - :type role_definition_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: SqlRoleDefinitionGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.SqlRoleDefinitionGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SqlRoleDefinitionGetResults] = kwargs.pop("cls", None) - - _request = build_get_sql_role_definition_request( - role_definition_id=role_definition_id, - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("SqlRoleDefinitionGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _create_update_sql_role_definition_initial( # pylint: disable=name-too-long - self, - role_definition_id: str, - resource_group_name: str, - account_name: str, - create_update_sql_role_definition_parameters: Union[_models.SqlRoleDefinitionCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_sql_role_definition_parameters, (IOBase, bytes)): - _content = create_update_sql_role_definition_parameters - else: - _json = self._serialize.body( - create_update_sql_role_definition_parameters, "SqlRoleDefinitionCreateUpdateParameters" - ) - - _request = build_create_update_sql_role_definition_request( - role_definition_id=role_definition_id, - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_update_sql_role_definition( - self, - role_definition_id: str, - resource_group_name: str, - account_name: str, - create_update_sql_role_definition_parameters: _models.SqlRoleDefinitionCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.SqlRoleDefinitionGetResults]: - """Creates or updates an Azure Cosmos DB SQL Role Definition. - - :param role_definition_id: The GUID for the Role Definition. Required. - :type role_definition_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param create_update_sql_role_definition_parameters: The properties required to create or - update a Role Definition. Required. - :type create_update_sql_role_definition_parameters: - ~azure.mgmt.cosmosdb.models.SqlRoleDefinitionCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either SqlRoleDefinitionGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlRoleDefinitionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_update_sql_role_definition( - self, - role_definition_id: str, - resource_group_name: str, - account_name: str, - create_update_sql_role_definition_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.SqlRoleDefinitionGetResults]: - """Creates or updates an Azure Cosmos DB SQL Role Definition. - - :param role_definition_id: The GUID for the Role Definition. Required. - :type role_definition_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param create_update_sql_role_definition_parameters: The properties required to create or - update a Role Definition. Required. - :type create_update_sql_role_definition_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either SqlRoleDefinitionGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlRoleDefinitionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_update_sql_role_definition( - self, - role_definition_id: str, - resource_group_name: str, - account_name: str, - create_update_sql_role_definition_parameters: Union[_models.SqlRoleDefinitionCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.SqlRoleDefinitionGetResults]: - """Creates or updates an Azure Cosmos DB SQL Role Definition. - - :param role_definition_id: The GUID for the Role Definition. Required. - :type role_definition_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param create_update_sql_role_definition_parameters: The properties required to create or - update a Role Definition. Is either a SqlRoleDefinitionCreateUpdateParameters type or a - IO[bytes] type. Required. - :type create_update_sql_role_definition_parameters: - ~azure.mgmt.cosmosdb.models.SqlRoleDefinitionCreateUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either SqlRoleDefinitionGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlRoleDefinitionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SqlRoleDefinitionGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_update_sql_role_definition_initial( - role_definition_id=role_definition_id, - resource_group_name=resource_group_name, - account_name=account_name, - create_update_sql_role_definition_parameters=create_update_sql_role_definition_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("SqlRoleDefinitionGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.SqlRoleDefinitionGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.SqlRoleDefinitionGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _delete_sql_role_definition_initial( - self, role_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_sql_role_definition_request( - role_definition_id=role_definition_id, - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202, 204]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete_sql_role_definition( - self, role_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any - ) -> LROPoller[None]: - """Deletes an existing Azure Cosmos DB SQL Role Definition. - - :param role_definition_id: The GUID for the Role Definition. Required. - :type role_definition_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_sql_role_definition_initial( - role_definition_id=role_definition_id, - resource_group_name=resource_group_name, - account_name=account_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace - def list_sql_role_definitions( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> Iterable["_models.SqlRoleDefinitionGetResults"]: - """Retrieves the list of all Azure Cosmos DB SQL Role Definitions. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either SqlRoleDefinitionGetResults or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.SqlRoleDefinitionGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SqlRoleDefinitionListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_sql_role_definitions_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("SqlRoleDefinitionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get_sql_role_assignment( - self, role_assignment_id: str, resource_group_name: str, account_name: str, **kwargs: Any - ) -> _models.SqlRoleAssignmentGetResults: - """Retrieves the properties of an existing Azure Cosmos DB SQL Role Assignment with the given Id. - - :param role_assignment_id: The GUID for the Role Assignment. Required. - :type role_assignment_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: SqlRoleAssignmentGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.SqlRoleAssignmentGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SqlRoleAssignmentGetResults] = kwargs.pop("cls", None) - - _request = build_get_sql_role_assignment_request( - role_assignment_id=role_assignment_id, - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("SqlRoleAssignmentGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _create_update_sql_role_assignment_initial( # pylint: disable=name-too-long - self, - role_assignment_id: str, - resource_group_name: str, - account_name: str, - create_update_sql_role_assignment_parameters: Union[_models.SqlRoleAssignmentCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_sql_role_assignment_parameters, (IOBase, bytes)): - _content = create_update_sql_role_assignment_parameters - else: - _json = self._serialize.body( - create_update_sql_role_assignment_parameters, "SqlRoleAssignmentCreateUpdateParameters" - ) - - _request = build_create_update_sql_role_assignment_request( - role_assignment_id=role_assignment_id, - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_update_sql_role_assignment( - self, - role_assignment_id: str, - resource_group_name: str, - account_name: str, - create_update_sql_role_assignment_parameters: _models.SqlRoleAssignmentCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.SqlRoleAssignmentGetResults]: - """Creates or updates an Azure Cosmos DB SQL Role Assignment. - - :param role_assignment_id: The GUID for the Role Assignment. Required. - :type role_assignment_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param create_update_sql_role_assignment_parameters: The properties required to create or - update a Role Assignment. Required. - :type create_update_sql_role_assignment_parameters: - ~azure.mgmt.cosmosdb.models.SqlRoleAssignmentCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either SqlRoleAssignmentGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlRoleAssignmentGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_update_sql_role_assignment( - self, - role_assignment_id: str, - resource_group_name: str, - account_name: str, - create_update_sql_role_assignment_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.SqlRoleAssignmentGetResults]: - """Creates or updates an Azure Cosmos DB SQL Role Assignment. - - :param role_assignment_id: The GUID for the Role Assignment. Required. - :type role_assignment_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param create_update_sql_role_assignment_parameters: The properties required to create or - update a Role Assignment. Required. - :type create_update_sql_role_assignment_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either SqlRoleAssignmentGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlRoleAssignmentGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_update_sql_role_assignment( - self, - role_assignment_id: str, - resource_group_name: str, - account_name: str, - create_update_sql_role_assignment_parameters: Union[_models.SqlRoleAssignmentCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.SqlRoleAssignmentGetResults]: - """Creates or updates an Azure Cosmos DB SQL Role Assignment. - - :param role_assignment_id: The GUID for the Role Assignment. Required. - :type role_assignment_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param create_update_sql_role_assignment_parameters: The properties required to create or - update a Role Assignment. Is either a SqlRoleAssignmentCreateUpdateParameters type or a - IO[bytes] type. Required. - :type create_update_sql_role_assignment_parameters: - ~azure.mgmt.cosmosdb.models.SqlRoleAssignmentCreateUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either SqlRoleAssignmentGetResults or the result - of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlRoleAssignmentGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.SqlRoleAssignmentGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_update_sql_role_assignment_initial( - role_assignment_id=role_assignment_id, - resource_group_name=resource_group_name, - account_name=account_name, - create_update_sql_role_assignment_parameters=create_update_sql_role_assignment_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("SqlRoleAssignmentGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.SqlRoleAssignmentGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.SqlRoleAssignmentGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _delete_sql_role_assignment_initial( - self, role_assignment_id: str, resource_group_name: str, account_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_sql_role_assignment_request( - role_assignment_id=role_assignment_id, - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202, 204]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete_sql_role_assignment( - self, role_assignment_id: str, resource_group_name: str, account_name: str, **kwargs: Any - ) -> LROPoller[None]: - """Deletes an existing Azure Cosmos DB SQL Role Assignment. - - :param role_assignment_id: The GUID for the Role Assignment. Required. - :type role_assignment_id: str - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_sql_role_assignment_initial( - role_assignment_id=role_assignment_id, - resource_group_name=resource_group_name, - account_name=account_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace - def list_sql_role_assignments( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> Iterable["_models.SqlRoleAssignmentGetResults"]: - """Retrieves the list of all Azure Cosmos DB SQL Role Assignments. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either SqlRoleAssignmentGetResults or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.SqlRoleAssignmentGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SqlRoleAssignmentListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_sql_role_assignments_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("SqlRoleAssignmentListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - def _retrieve_continuous_backup_information_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(location, (IOBase, bytes)): - _content = location - else: - _json = self._serialize.body(location, "ContinuousBackupRestoreLocation") - - _request = build_retrieve_continuous_backup_information_request( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - location: _models.ContinuousBackupRestoreLocation, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.BackupInformation]: - """Retrieves continuous backup information for a container resource. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param location: The name of the continuous backup restore location. Required. - :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either BackupInformation or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - location: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.BackupInformation]: - """Retrieves continuous backup information for a container resource. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param location: The name of the continuous backup restore location. Required. - :type location: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either BackupInformation or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - database_name: str, - container_name: str, - location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.BackupInformation]: - """Retrieves continuous backup information for a container resource. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param database_name: Cosmos DB database name. Required. - :type database_name: str - :param container_name: Cosmos DB container name. Required. - :type container_name: str - :param location: The name of the continuous backup restore location. Is either a - ContinuousBackupRestoreLocation type or a IO[bytes] type. Required. - :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation or IO[bytes] - :return: An instance of LROPoller that returns either BackupInformation or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.BackupInformation] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._retrieve_continuous_backup_information_initial( - resource_group_name=resource_group_name, - account_name=account_name, - database_name=database_name, - container_name=container_name, - location=location, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("BackupInformation", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.BackupInformation].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.BackupInformation]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_sql_databases_request( + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_sql_database_request( + resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_update_sql_database_request( + resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_sql_database_request( + resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_get_sql_database_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/throughputSettings/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_sql_database_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/throughputSettings/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_migrate_sql_database_to_autoscale_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/throughputSettings/default/migrateToAutoscale", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_migrate_sql_database_to_manual_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/throughputSettings/default/migrateToManualThroughput", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_client_encryption_keys_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/clientEncryptionKeys", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_client_encryption_key_request( + resource_group_name: str, + account_name: str, + database_name: str, + client_encryption_key_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/clientEncryptionKeys/{clientEncryptionKeyName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "clientEncryptionKeyName": _SERIALIZER.url("client_encryption_key_name", client_encryption_key_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_update_client_encryption_key_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + database_name: str, + client_encryption_key_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/clientEncryptionKeys/{clientEncryptionKeyName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "clientEncryptionKeyName": _SERIALIZER.url("client_encryption_key_name", client_encryption_key_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_sql_containers_request( + resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_sql_container_request( + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "containerName": _SERIALIZER.url("container_name", container_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_update_sql_container_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "containerName": _SERIALIZER.url("container_name", container_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_sql_container_request( + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "containerName": _SERIALIZER.url("container_name", container_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_sql_database_partition_merge_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/partitionMerge", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_sql_container_partition_merge_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/partitionMerge", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "containerName": _SERIALIZER.url("container_name", container_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_sql_container_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/throughputSettings/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "containerName": _SERIALIZER.url("container_name", container_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_sql_container_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/throughputSettings/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "containerName": _SERIALIZER.url("container_name", container_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_migrate_sql_container_to_autoscale_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/throughputSettings/default/migrateToAutoscale", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "containerName": _SERIALIZER.url("container_name", container_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_migrate_sql_container_to_manual_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/throughputSettings/default/migrateToManualThroughput", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "containerName": _SERIALIZER.url("container_name", container_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_sql_database_retrieve_throughput_distribution_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/throughputSettings/default/retrieveThroughputDistribution", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_sql_database_redistribute_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, database_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/throughputSettings/default/redistributeThroughput", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_sql_container_retrieve_throughput_distribution_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/throughputSettings/default/retrieveThroughputDistribution", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "containerName": _SERIALIZER.url("container_name", container_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_sql_container_redistribute_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/throughputSettings/default/redistributeThroughput", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "containerName": _SERIALIZER.url("container_name", container_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_sql_stored_procedures_request( + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/storedProcedures", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "containerName": _SERIALIZER.url("container_name", container_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_sql_stored_procedure_request( + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + stored_procedure_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/storedProcedures/{storedProcedureName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "containerName": _SERIALIZER.url("container_name", container_name, "str"), + "storedProcedureName": _SERIALIZER.url("stored_procedure_name", stored_procedure_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_update_sql_stored_procedure_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + stored_procedure_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/storedProcedures/{storedProcedureName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "containerName": _SERIALIZER.url("container_name", container_name, "str"), + "storedProcedureName": _SERIALIZER.url("stored_procedure_name", stored_procedure_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_sql_stored_procedure_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + stored_procedure_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/storedProcedures/{storedProcedureName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "containerName": _SERIALIZER.url("container_name", container_name, "str"), + "storedProcedureName": _SERIALIZER.url("stored_procedure_name", stored_procedure_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_list_sql_user_defined_functions_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/userDefinedFunctions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "containerName": _SERIALIZER.url("container_name", container_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_sql_user_defined_function_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + user_defined_function_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/userDefinedFunctions/{userDefinedFunctionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "containerName": _SERIALIZER.url("container_name", container_name, "str"), + "userDefinedFunctionName": _SERIALIZER.url("user_defined_function_name", user_defined_function_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_update_sql_user_defined_function_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + user_defined_function_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/userDefinedFunctions/{userDefinedFunctionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "containerName": _SERIALIZER.url("container_name", container_name, "str"), + "userDefinedFunctionName": _SERIALIZER.url("user_defined_function_name", user_defined_function_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_sql_user_defined_function_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + user_defined_function_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/userDefinedFunctions/{userDefinedFunctionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "containerName": _SERIALIZER.url("container_name", container_name, "str"), + "userDefinedFunctionName": _SERIALIZER.url("user_defined_function_name", user_defined_function_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_list_sql_triggers_request( + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/triggers", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "containerName": _SERIALIZER.url("container_name", container_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_sql_trigger_request( + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + trigger_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/triggers/{triggerName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "containerName": _SERIALIZER.url("container_name", container_name, "str"), + "triggerName": _SERIALIZER.url("trigger_name", trigger_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_update_sql_trigger_request( + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + trigger_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/triggers/{triggerName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "containerName": _SERIALIZER.url("container_name", container_name, "str"), + "triggerName": _SERIALIZER.url("trigger_name", trigger_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_sql_trigger_request( + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + trigger_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/triggers/{triggerName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "containerName": _SERIALIZER.url("container_name", container_name, "str"), + "triggerName": _SERIALIZER.url("trigger_name", trigger_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_get_sql_role_definition_request( + role_definition_id: str, resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlRoleDefinitions/{roleDefinitionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "roleDefinitionId": _SERIALIZER.url("role_definition_id", role_definition_id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_update_sql_role_definition_request( # pylint: disable=name-too-long + role_definition_id: str, resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlRoleDefinitions/{roleDefinitionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "roleDefinitionId": _SERIALIZER.url("role_definition_id", role_definition_id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_sql_role_definition_request( + role_definition_id: str, resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlRoleDefinitions/{roleDefinitionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "roleDefinitionId": _SERIALIZER.url("role_definition_id", role_definition_id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_sql_role_definitions_request( + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlRoleDefinitions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_sql_role_assignment_request( + role_assignment_id: str, resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlRoleAssignments/{roleAssignmentId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "roleAssignmentId": _SERIALIZER.url("role_assignment_id", role_assignment_id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_update_sql_role_assignment_request( # pylint: disable=name-too-long + role_assignment_id: str, resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlRoleAssignments/{roleAssignmentId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "roleAssignmentId": _SERIALIZER.url("role_assignment_id", role_assignment_id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_sql_role_assignment_request( + role_assignment_id: str, resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlRoleAssignments/{roleAssignmentId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "roleAssignmentId": _SERIALIZER.url("role_assignment_id", role_assignment_id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_sql_role_assignments_request( + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlRoleAssignments", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_retrieve_continuous_backup_information_request( # pylint: disable=name-too-long + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/retrieveContinuousBackupInformation", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), + "containerName": _SERIALIZER.url("container_name", container_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class SqlResourcesOperations: # pylint: disable=too-many-public-methods + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`sql_resources` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_sql_databases( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> Iterable["_models.SqlDatabaseGetResults"]: + """Lists the SQL databases under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either SqlDatabaseGetResults or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.SqlDatabaseGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SqlDatabaseListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_sql_databases_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("SqlDatabaseListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get_sql_database( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> _models.SqlDatabaseGetResults: + """Gets the SQL database under an existing Azure Cosmos DB database account with the provided + name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: SqlDatabaseGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.SqlDatabaseGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SqlDatabaseGetResults] = kwargs.pop("cls", None) + + _request = build_get_sql_database_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("SqlDatabaseGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_update_sql_database_initial( + self, + resource_group_name: str, + account_name: str, + database_name: str, + create_update_sql_database_parameters: Union[_models.SqlDatabaseCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_sql_database_parameters, (IOBase, bytes)): + _content = create_update_sql_database_parameters + else: + _json = self._serialize.body(create_update_sql_database_parameters, "SqlDatabaseCreateUpdateParameters") + + _request = build_create_update_sql_database_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_update_sql_database( + self, + resource_group_name: str, + account_name: str, + database_name: str, + create_update_sql_database_parameters: _models.SqlDatabaseCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.SqlDatabaseGetResults]: + """Create or update an Azure Cosmos DB SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param create_update_sql_database_parameters: The parameters to provide for the current SQL + database. Required. + :type create_update_sql_database_parameters: + ~azure.mgmt.cosmosdb.models.SqlDatabaseCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either SqlDatabaseGetResults or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlDatabaseGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_update_sql_database( + self, + resource_group_name: str, + account_name: str, + database_name: str, + create_update_sql_database_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.SqlDatabaseGetResults]: + """Create or update an Azure Cosmos DB SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param create_update_sql_database_parameters: The parameters to provide for the current SQL + database. Required. + :type create_update_sql_database_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either SqlDatabaseGetResults or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlDatabaseGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_update_sql_database( + self, + resource_group_name: str, + account_name: str, + database_name: str, + create_update_sql_database_parameters: Union[_models.SqlDatabaseCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.SqlDatabaseGetResults]: + """Create or update an Azure Cosmos DB SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param create_update_sql_database_parameters: The parameters to provide for the current SQL + database. Is either a SqlDatabaseCreateUpdateParameters type or a IO[bytes] type. Required. + :type create_update_sql_database_parameters: + ~azure.mgmt.cosmosdb.models.SqlDatabaseCreateUpdateParameters or IO[bytes] + :return: An instance of LROPoller that returns either SqlDatabaseGetResults or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlDatabaseGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.SqlDatabaseGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_update_sql_database_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + create_update_sql_database_parameters=create_update_sql_database_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("SqlDatabaseGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.SqlDatabaseGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.SqlDatabaseGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_sql_database_initial( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_sql_database_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete_sql_database( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Deletes an existing Azure Cosmos DB SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_sql_database_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def get_sql_database_throughput( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> _models.ThroughputSettingsGetResults: + """Gets the RUs per second of the SQL database under an existing Azure Cosmos DB database account + with the provided name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: ThroughputSettingsGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + + _request = build_get_sql_database_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _update_sql_database_throughput_initial( + self, + resource_group_name: str, + account_name: str, + database_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(update_throughput_parameters, (IOBase, bytes)): + _content = update_throughput_parameters + else: + _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") + + _request = build_update_sql_database_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_update_sql_database_throughput( + self, + resource_group_name: str, + account_name: str, + database_name: str, + update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param update_throughput_parameters: The parameters to provide for the RUs per second of the + current SQL database. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update_sql_database_throughput( + self, + resource_group_name: str, + account_name: str, + database_name: str, + update_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param update_throughput_parameters: The parameters to provide for the RUs per second of the + current SQL database. Required. + :type update_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update_sql_database_throughput( + self, + resource_group_name: str, + account_name: str, + database_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param update_throughput_parameters: The parameters to provide for the RUs per second of the + current SQL database. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] type. + Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._update_sql_database_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + update_throughput_parameters=update_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _migrate_sql_database_to_autoscale_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_sql_database_to_autoscale_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_migrate_sql_database_to_autoscale( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB SQL database from manual throughput to autoscale. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._migrate_sql_database_to_autoscale_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _migrate_sql_database_to_manual_throughput_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_sql_database_to_manual_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_migrate_sql_database_to_manual_throughput( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB SQL database from autoscale to manual throughput. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._migrate_sql_database_to_manual_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def list_client_encryption_keys( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> Iterable["_models.ClientEncryptionKeyGetResults"]: + """Lists the ClientEncryptionKeys under an existing Azure Cosmos DB SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: An iterator like instance of either ClientEncryptionKeyGetResults or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.ClientEncryptionKeyGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ClientEncryptionKeysListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_client_encryption_keys_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ClientEncryptionKeysListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get_client_encryption_key( + self, + resource_group_name: str, + account_name: str, + database_name: str, + client_encryption_key_name: str, + **kwargs: Any + ) -> _models.ClientEncryptionKeyGetResults: + """Gets the ClientEncryptionKey under an existing Azure Cosmos DB SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param client_encryption_key_name: Cosmos DB ClientEncryptionKey name. Required. + :type client_encryption_key_name: str + :return: ClientEncryptionKeyGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ClientEncryptionKeyGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ClientEncryptionKeyGetResults] = kwargs.pop("cls", None) + + _request = build_get_client_encryption_key_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + client_encryption_key_name=client_encryption_key_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ClientEncryptionKeyGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_update_client_encryption_key_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + client_encryption_key_name: str, + create_update_client_encryption_key_parameters: Union[ + _models.ClientEncryptionKeyCreateUpdateParameters, IO[bytes] + ], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_client_encryption_key_parameters, (IOBase, bytes)): + _content = create_update_client_encryption_key_parameters + else: + _json = self._serialize.body( + create_update_client_encryption_key_parameters, "ClientEncryptionKeyCreateUpdateParameters" + ) + + _request = build_create_update_client_encryption_key_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + client_encryption_key_name=client_encryption_key_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_update_client_encryption_key( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + client_encryption_key_name: str, + create_update_client_encryption_key_parameters: _models.ClientEncryptionKeyCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ClientEncryptionKeyGetResults]: + """Create or update a ClientEncryptionKey. This API is meant to be invoked via tools such as the + Azure Powershell (instead of directly). + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param client_encryption_key_name: Cosmos DB ClientEncryptionKey name. Required. + :type client_encryption_key_name: str + :param create_update_client_encryption_key_parameters: The parameters to provide for the client + encryption key. Required. + :type create_update_client_encryption_key_parameters: + ~azure.mgmt.cosmosdb.models.ClientEncryptionKeyCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ClientEncryptionKeyGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ClientEncryptionKeyGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_update_client_encryption_key( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + client_encryption_key_name: str, + create_update_client_encryption_key_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ClientEncryptionKeyGetResults]: + """Create or update a ClientEncryptionKey. This API is meant to be invoked via tools such as the + Azure Powershell (instead of directly). + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param client_encryption_key_name: Cosmos DB ClientEncryptionKey name. Required. + :type client_encryption_key_name: str + :param create_update_client_encryption_key_parameters: The parameters to provide for the client + encryption key. Required. + :type create_update_client_encryption_key_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ClientEncryptionKeyGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ClientEncryptionKeyGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_update_client_encryption_key( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + client_encryption_key_name: str, + create_update_client_encryption_key_parameters: Union[ + _models.ClientEncryptionKeyCreateUpdateParameters, IO[bytes] + ], + **kwargs: Any + ) -> LROPoller[_models.ClientEncryptionKeyGetResults]: + """Create or update a ClientEncryptionKey. This API is meant to be invoked via tools such as the + Azure Powershell (instead of directly). + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param client_encryption_key_name: Cosmos DB ClientEncryptionKey name. Required. + :type client_encryption_key_name: str + :param create_update_client_encryption_key_parameters: The parameters to provide for the client + encryption key. Is either a ClientEncryptionKeyCreateUpdateParameters type or a IO[bytes] type. + Required. + :type create_update_client_encryption_key_parameters: + ~azure.mgmt.cosmosdb.models.ClientEncryptionKeyCreateUpdateParameters or IO[bytes] + :return: An instance of LROPoller that returns either ClientEncryptionKeyGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ClientEncryptionKeyGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ClientEncryptionKeyGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_update_client_encryption_key_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + client_encryption_key_name=client_encryption_key_name, + create_update_client_encryption_key_parameters=create_update_client_encryption_key_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ClientEncryptionKeyGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ClientEncryptionKeyGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ClientEncryptionKeyGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def list_sql_containers( + self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any + ) -> Iterable["_models.SqlContainerGetResults"]: + """Lists the SQL container under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :return: An iterator like instance of either SqlContainerGetResults or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.SqlContainerGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SqlContainerListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_sql_containers_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("SqlContainerListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get_sql_container( + self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any + ) -> _models.SqlContainerGetResults: + """Gets the SQL container under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :return: SqlContainerGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.SqlContainerGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SqlContainerGetResults] = kwargs.pop("cls", None) + + _request = build_get_sql_container_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("SqlContainerGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_update_sql_container_initial( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + create_update_sql_container_parameters: Union[_models.SqlContainerCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_sql_container_parameters, (IOBase, bytes)): + _content = create_update_sql_container_parameters + else: + _json = self._serialize.body(create_update_sql_container_parameters, "SqlContainerCreateUpdateParameters") + + _request = build_create_update_sql_container_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_update_sql_container( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + create_update_sql_container_parameters: _models.SqlContainerCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.SqlContainerGetResults]: + """Create or update an Azure Cosmos DB SQL container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param create_update_sql_container_parameters: The parameters to provide for the current SQL + container. Required. + :type create_update_sql_container_parameters: + ~azure.mgmt.cosmosdb.models.SqlContainerCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either SqlContainerGetResults or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlContainerGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_update_sql_container( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + create_update_sql_container_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.SqlContainerGetResults]: + """Create or update an Azure Cosmos DB SQL container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param create_update_sql_container_parameters: The parameters to provide for the current SQL + container. Required. + :type create_update_sql_container_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either SqlContainerGetResults or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlContainerGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_update_sql_container( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + create_update_sql_container_parameters: Union[_models.SqlContainerCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.SqlContainerGetResults]: + """Create or update an Azure Cosmos DB SQL container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param create_update_sql_container_parameters: The parameters to provide for the current SQL + container. Is either a SqlContainerCreateUpdateParameters type or a IO[bytes] type. Required. + :type create_update_sql_container_parameters: + ~azure.mgmt.cosmosdb.models.SqlContainerCreateUpdateParameters or IO[bytes] + :return: An instance of LROPoller that returns either SqlContainerGetResults or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlContainerGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.SqlContainerGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_update_sql_container_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + create_update_sql_container_parameters=create_update_sql_container_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("SqlContainerGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.SqlContainerGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.SqlContainerGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_sql_container_initial( + self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_sql_container_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete_sql_container( + self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Deletes an existing Azure Cosmos DB SQL container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_sql_container_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + def _sql_database_partition_merge_initial( + self, + resource_group_name: str, + account_name: str, + database_name: str, + merge_parameters: Union[_models.MergeParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(merge_parameters, (IOBase, bytes)): + _content = merge_parameters + else: + _json = self._serialize.body(merge_parameters, "MergeParameters") + + _request = build_sql_database_partition_merge_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_sql_database_partition_merge( + self, + resource_group_name: str, + account_name: str, + database_name: str, + merge_parameters: _models.MergeParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionStorageInfoCollection]: + """Merges the partitions of a SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param merge_parameters: The parameters for the merge operation. Required. + :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either PhysicalPartitionStorageInfoCollection or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_sql_database_partition_merge( + self, + resource_group_name: str, + account_name: str, + database_name: str, + merge_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionStorageInfoCollection]: + """Merges the partitions of a SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param merge_parameters: The parameters for the merge operation. Required. + :type merge_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either PhysicalPartitionStorageInfoCollection or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_sql_database_partition_merge( + self, + resource_group_name: str, + account_name: str, + database_name: str, + merge_parameters: Union[_models.MergeParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionStorageInfoCollection]: + """Merges the partitions of a SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param merge_parameters: The parameters for the merge operation. Is either a MergeParameters + type or a IO[bytes] type. Required. + :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters or IO[bytes] + :return: An instance of LROPoller that returns either PhysicalPartitionStorageInfoCollection or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PhysicalPartitionStorageInfoCollection] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._sql_database_partition_merge_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + merge_parameters=merge_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("PhysicalPartitionStorageInfoCollection", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.PhysicalPartitionStorageInfoCollection].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.PhysicalPartitionStorageInfoCollection]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _list_sql_container_partition_merge_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + merge_parameters: Union[_models.MergeParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(merge_parameters, (IOBase, bytes)): + _content = merge_parameters + else: + _json = self._serialize.body(merge_parameters, "MergeParameters") + + _request = build_list_sql_container_partition_merge_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_list_sql_container_partition_merge( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + merge_parameters: _models.MergeParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionStorageInfoCollection]: + """Merges the partitions of a SQL Container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param merge_parameters: The parameters for the merge operation. Required. + :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either PhysicalPartitionStorageInfoCollection or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_list_sql_container_partition_merge( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + merge_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionStorageInfoCollection]: + """Merges the partitions of a SQL Container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param merge_parameters: The parameters for the merge operation. Required. + :type merge_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either PhysicalPartitionStorageInfoCollection or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_list_sql_container_partition_merge( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + merge_parameters: Union[_models.MergeParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionStorageInfoCollection]: + """Merges the partitions of a SQL Container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param merge_parameters: The parameters for the merge operation. Is either a MergeParameters + type or a IO[bytes] type. Required. + :type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters or IO[bytes] + :return: An instance of LROPoller that returns either PhysicalPartitionStorageInfoCollection or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PhysicalPartitionStorageInfoCollection] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._list_sql_container_partition_merge_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + merge_parameters=merge_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("PhysicalPartitionStorageInfoCollection", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.PhysicalPartitionStorageInfoCollection].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.PhysicalPartitionStorageInfoCollection]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def get_sql_container_throughput( + self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any + ) -> _models.ThroughputSettingsGetResults: + """Gets the RUs per second of the SQL container under an existing Azure Cosmos DB database + account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :return: ThroughputSettingsGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + + _request = build_get_sql_container_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _update_sql_container_throughput_initial( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(update_throughput_parameters, (IOBase, bytes)): + _content = update_throughput_parameters + else: + _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") + + _request = build_update_sql_container_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_update_sql_container_throughput( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB SQL container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param update_throughput_parameters: The parameters to provide for the RUs per second of the + current SQL container. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update_sql_container_throughput( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + update_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB SQL container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param update_throughput_parameters: The parameters to provide for the RUs per second of the + current SQL container. Required. + :type update_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update_sql_container_throughput( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB SQL container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param update_throughput_parameters: The parameters to provide for the RUs per second of the + current SQL container. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] type. + Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._update_sql_container_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + update_throughput_parameters=update_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _migrate_sql_container_to_autoscale_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_sql_container_to_autoscale_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_migrate_sql_container_to_autoscale( + self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB SQL container from manual throughput to autoscale. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._migrate_sql_container_to_autoscale_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _migrate_sql_container_to_manual_throughput_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_sql_container_to_manual_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_migrate_sql_container_to_manual_throughput( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB SQL container from autoscale to manual throughput. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._migrate_sql_container_to_manual_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _sql_database_retrieve_throughput_distribution_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(retrieve_throughput_parameters, (IOBase, bytes)): + _content = retrieve_throughput_parameters + else: + _json = self._serialize.body(retrieve_throughput_parameters, "RetrieveThroughputParameters") + + _request = build_sql_database_retrieve_throughput_distribution_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_sql_database_retrieve_throughput_distribution( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + retrieve_throughput_parameters: _models.RetrieveThroughputParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Retrieve throughput distribution for an Azure Cosmos DB SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput + distribution for the current SQL database. Required. + :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_sql_database_retrieve_throughput_distribution( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + retrieve_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Retrieve throughput distribution for an Azure Cosmos DB SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput + distribution for the current SQL database. Required. + :type retrieve_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_sql_database_retrieve_throughput_distribution( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Retrieve throughput distribution for an Azure Cosmos DB SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput + distribution for the current SQL database. Is either a RetrieveThroughputParameters type or a + IO[bytes] type. Required. + :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters + or IO[bytes] + :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._sql_database_retrieve_throughput_distribution_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + retrieve_throughput_parameters=retrieve_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.PhysicalPartitionThroughputInfoResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _sql_database_redistribute_throughput_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(redistribute_throughput_parameters, (IOBase, bytes)): + _content = redistribute_throughput_parameters + else: + _json = self._serialize.body(redistribute_throughput_parameters, "RedistributeThroughputParameters") + + _request = build_sql_database_redistribute_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_sql_database_redistribute_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + redistribute_throughput_parameters: _models.RedistributeThroughputParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Redistribute throughput for an Azure Cosmos DB SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param redistribute_throughput_parameters: The parameters to provide for redistributing + throughput for the current SQL database. Required. + :type redistribute_throughput_parameters: + ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_sql_database_redistribute_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + redistribute_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Redistribute throughput for an Azure Cosmos DB SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param redistribute_throughput_parameters: The parameters to provide for redistributing + throughput for the current SQL database. Required. + :type redistribute_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_sql_database_redistribute_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Redistribute throughput for an Azure Cosmos DB SQL database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param redistribute_throughput_parameters: The parameters to provide for redistributing + throughput for the current SQL database. Is either a RedistributeThroughputParameters type or a + IO[bytes] type. Required. + :type redistribute_throughput_parameters: + ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters or IO[bytes] + :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._sql_database_redistribute_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + redistribute_throughput_parameters=redistribute_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.PhysicalPartitionThroughputInfoResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _sql_container_retrieve_throughput_distribution_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(retrieve_throughput_parameters, (IOBase, bytes)): + _content = retrieve_throughput_parameters + else: + _json = self._serialize.body(retrieve_throughput_parameters, "RetrieveThroughputParameters") + + _request = build_sql_container_retrieve_throughput_distribution_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_sql_container_retrieve_throughput_distribution( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + retrieve_throughput_parameters: _models.RetrieveThroughputParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Retrieve throughput distribution for an Azure Cosmos DB SQL container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput + distribution for the current SQL container. Required. + :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_sql_container_retrieve_throughput_distribution( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + retrieve_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Retrieve throughput distribution for an Azure Cosmos DB SQL container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput + distribution for the current SQL container. Required. + :type retrieve_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_sql_container_retrieve_throughput_distribution( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Retrieve throughput distribution for an Azure Cosmos DB SQL container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param retrieve_throughput_parameters: The parameters to provide for retrieving throughput + distribution for the current SQL container. Is either a RetrieveThroughputParameters type or a + IO[bytes] type. Required. + :type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters + or IO[bytes] + :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._sql_container_retrieve_throughput_distribution_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + retrieve_throughput_parameters=retrieve_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.PhysicalPartitionThroughputInfoResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _sql_container_redistribute_throughput_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(redistribute_throughput_parameters, (IOBase, bytes)): + _content = redistribute_throughput_parameters + else: + _json = self._serialize.body(redistribute_throughput_parameters, "RedistributeThroughputParameters") + + _request = build_sql_container_redistribute_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_sql_container_redistribute_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + redistribute_throughput_parameters: _models.RedistributeThroughputParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Redistribute throughput for an Azure Cosmos DB SQL container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param redistribute_throughput_parameters: The parameters to provide for redistributing + throughput for the current SQL container. Required. + :type redistribute_throughput_parameters: + ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_sql_container_redistribute_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + redistribute_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Redistribute throughput for an Azure Cosmos DB SQL container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param redistribute_throughput_parameters: The parameters to provide for redistributing + throughput for the current SQL container. Required. + :type redistribute_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_sql_container_redistribute_throughput( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.PhysicalPartitionThroughputInfoResult]: + """Redistribute throughput for an Azure Cosmos DB SQL container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param redistribute_throughput_parameters: The parameters to provide for redistributing + throughput for the current SQL container. Is either a RedistributeThroughputParameters type or + a IO[bytes] type. Required. + :type redistribute_throughput_parameters: + ~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters or IO[bytes] + :return: An instance of LROPoller that returns either PhysicalPartitionThroughputInfoResult or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._sql_container_redistribute_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + redistribute_throughput_parameters=redistribute_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.PhysicalPartitionThroughputInfoResult].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.PhysicalPartitionThroughputInfoResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def list_sql_stored_procedures( + self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any + ) -> Iterable["_models.SqlStoredProcedureGetResults"]: + """Lists the SQL storedProcedure under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :return: An iterator like instance of either SqlStoredProcedureGetResults or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.SqlStoredProcedureGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SqlStoredProcedureListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_sql_stored_procedures_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("SqlStoredProcedureListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get_sql_stored_procedure( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + stored_procedure_name: str, + **kwargs: Any + ) -> _models.SqlStoredProcedureGetResults: + """Gets the SQL storedProcedure under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param stored_procedure_name: Cosmos DB storedProcedure name. Required. + :type stored_procedure_name: str + :return: SqlStoredProcedureGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.SqlStoredProcedureGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SqlStoredProcedureGetResults] = kwargs.pop("cls", None) + + _request = build_get_sql_stored_procedure_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + stored_procedure_name=stored_procedure_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("SqlStoredProcedureGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_update_sql_stored_procedure_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + stored_procedure_name: str, + create_update_sql_stored_procedure_parameters: Union[ + _models.SqlStoredProcedureCreateUpdateParameters, IO[bytes] + ], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_sql_stored_procedure_parameters, (IOBase, bytes)): + _content = create_update_sql_stored_procedure_parameters + else: + _json = self._serialize.body( + create_update_sql_stored_procedure_parameters, "SqlStoredProcedureCreateUpdateParameters" + ) + + _request = build_create_update_sql_stored_procedure_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + stored_procedure_name=stored_procedure_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_update_sql_stored_procedure( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + stored_procedure_name: str, + create_update_sql_stored_procedure_parameters: _models.SqlStoredProcedureCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.SqlStoredProcedureGetResults]: + """Create or update an Azure Cosmos DB SQL storedProcedure. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param stored_procedure_name: Cosmos DB storedProcedure name. Required. + :type stored_procedure_name: str + :param create_update_sql_stored_procedure_parameters: The parameters to provide for the current + SQL storedProcedure. Required. + :type create_update_sql_stored_procedure_parameters: + ~azure.mgmt.cosmosdb.models.SqlStoredProcedureCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either SqlStoredProcedureGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlStoredProcedureGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_update_sql_stored_procedure( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + stored_procedure_name: str, + create_update_sql_stored_procedure_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.SqlStoredProcedureGetResults]: + """Create or update an Azure Cosmos DB SQL storedProcedure. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param stored_procedure_name: Cosmos DB storedProcedure name. Required. + :type stored_procedure_name: str + :param create_update_sql_stored_procedure_parameters: The parameters to provide for the current + SQL storedProcedure. Required. + :type create_update_sql_stored_procedure_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either SqlStoredProcedureGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlStoredProcedureGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_update_sql_stored_procedure( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + stored_procedure_name: str, + create_update_sql_stored_procedure_parameters: Union[ + _models.SqlStoredProcedureCreateUpdateParameters, IO[bytes] + ], + **kwargs: Any + ) -> LROPoller[_models.SqlStoredProcedureGetResults]: + """Create or update an Azure Cosmos DB SQL storedProcedure. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param stored_procedure_name: Cosmos DB storedProcedure name. Required. + :type stored_procedure_name: str + :param create_update_sql_stored_procedure_parameters: The parameters to provide for the current + SQL storedProcedure. Is either a SqlStoredProcedureCreateUpdateParameters type or a IO[bytes] + type. Required. + :type create_update_sql_stored_procedure_parameters: + ~azure.mgmt.cosmosdb.models.SqlStoredProcedureCreateUpdateParameters or IO[bytes] + :return: An instance of LROPoller that returns either SqlStoredProcedureGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlStoredProcedureGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.SqlStoredProcedureGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_update_sql_stored_procedure_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + stored_procedure_name=stored_procedure_name, + create_update_sql_stored_procedure_parameters=create_update_sql_stored_procedure_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("SqlStoredProcedureGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.SqlStoredProcedureGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.SqlStoredProcedureGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_sql_stored_procedure_initial( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + stored_procedure_name: str, + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_sql_stored_procedure_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + stored_procedure_name=stored_procedure_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete_sql_stored_procedure( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + stored_procedure_name: str, + **kwargs: Any + ) -> LROPoller[None]: + """Deletes an existing Azure Cosmos DB SQL storedProcedure. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param stored_procedure_name: Cosmos DB storedProcedure name. Required. + :type stored_procedure_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_sql_stored_procedure_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + stored_procedure_name=stored_procedure_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def list_sql_user_defined_functions( + self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any + ) -> Iterable["_models.SqlUserDefinedFunctionGetResults"]: + """Lists the SQL userDefinedFunction under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :return: An iterator like instance of either SqlUserDefinedFunctionGetResults or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SqlUserDefinedFunctionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_sql_user_defined_functions_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("SqlUserDefinedFunctionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get_sql_user_defined_function( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + user_defined_function_name: str, + **kwargs: Any + ) -> _models.SqlUserDefinedFunctionGetResults: + """Gets the SQL userDefinedFunction under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param user_defined_function_name: Cosmos DB userDefinedFunction name. Required. + :type user_defined_function_name: str + :return: SqlUserDefinedFunctionGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SqlUserDefinedFunctionGetResults] = kwargs.pop("cls", None) + + _request = build_get_sql_user_defined_function_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + user_defined_function_name=user_defined_function_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("SqlUserDefinedFunctionGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_update_sql_user_defined_function_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + user_defined_function_name: str, + create_update_sql_user_defined_function_parameters: Union[ + _models.SqlUserDefinedFunctionCreateUpdateParameters, IO[bytes] + ], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_sql_user_defined_function_parameters, (IOBase, bytes)): + _content = create_update_sql_user_defined_function_parameters + else: + _json = self._serialize.body( + create_update_sql_user_defined_function_parameters, "SqlUserDefinedFunctionCreateUpdateParameters" + ) + + _request = build_create_update_sql_user_defined_function_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + user_defined_function_name=user_defined_function_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_update_sql_user_defined_function( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + user_defined_function_name: str, + create_update_sql_user_defined_function_parameters: _models.SqlUserDefinedFunctionCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.SqlUserDefinedFunctionGetResults]: + """Create or update an Azure Cosmos DB SQL userDefinedFunction. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param user_defined_function_name: Cosmos DB userDefinedFunction name. Required. + :type user_defined_function_name: str + :param create_update_sql_user_defined_function_parameters: The parameters to provide for the + current SQL userDefinedFunction. Required. + :type create_update_sql_user_defined_function_parameters: + ~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either SqlUserDefinedFunctionGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_update_sql_user_defined_function( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + user_defined_function_name: str, + create_update_sql_user_defined_function_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.SqlUserDefinedFunctionGetResults]: + """Create or update an Azure Cosmos DB SQL userDefinedFunction. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param user_defined_function_name: Cosmos DB userDefinedFunction name. Required. + :type user_defined_function_name: str + :param create_update_sql_user_defined_function_parameters: The parameters to provide for the + current SQL userDefinedFunction. Required. + :type create_update_sql_user_defined_function_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either SqlUserDefinedFunctionGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_update_sql_user_defined_function( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + user_defined_function_name: str, + create_update_sql_user_defined_function_parameters: Union[ + _models.SqlUserDefinedFunctionCreateUpdateParameters, IO[bytes] + ], + **kwargs: Any + ) -> LROPoller[_models.SqlUserDefinedFunctionGetResults]: + """Create or update an Azure Cosmos DB SQL userDefinedFunction. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param user_defined_function_name: Cosmos DB userDefinedFunction name. Required. + :type user_defined_function_name: str + :param create_update_sql_user_defined_function_parameters: The parameters to provide for the + current SQL userDefinedFunction. Is either a SqlUserDefinedFunctionCreateUpdateParameters type + or a IO[bytes] type. Required. + :type create_update_sql_user_defined_function_parameters: + ~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionCreateUpdateParameters or IO[bytes] + :return: An instance of LROPoller that returns either SqlUserDefinedFunctionGetResults or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlUserDefinedFunctionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.SqlUserDefinedFunctionGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_update_sql_user_defined_function_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + user_defined_function_name=user_defined_function_name, + create_update_sql_user_defined_function_parameters=create_update_sql_user_defined_function_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("SqlUserDefinedFunctionGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.SqlUserDefinedFunctionGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.SqlUserDefinedFunctionGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_sql_user_defined_function_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + user_defined_function_name: str, + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_sql_user_defined_function_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + user_defined_function_name=user_defined_function_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete_sql_user_defined_function( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + user_defined_function_name: str, + **kwargs: Any + ) -> LROPoller[None]: + """Deletes an existing Azure Cosmos DB SQL userDefinedFunction. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param user_defined_function_name: Cosmos DB userDefinedFunction name. Required. + :type user_defined_function_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_sql_user_defined_function_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + user_defined_function_name=user_defined_function_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def list_sql_triggers( + self, resource_group_name: str, account_name: str, database_name: str, container_name: str, **kwargs: Any + ) -> Iterable["_models.SqlTriggerGetResults"]: + """Lists the SQL trigger under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :return: An iterator like instance of either SqlTriggerGetResults or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.SqlTriggerGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SqlTriggerListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_sql_triggers_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("SqlTriggerListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get_sql_trigger( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + trigger_name: str, + **kwargs: Any + ) -> _models.SqlTriggerGetResults: + """Gets the SQL trigger under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param trigger_name: Cosmos DB trigger name. Required. + :type trigger_name: str + :return: SqlTriggerGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.SqlTriggerGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SqlTriggerGetResults] = kwargs.pop("cls", None) + + _request = build_get_sql_trigger_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + trigger_name=trigger_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("SqlTriggerGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_update_sql_trigger_initial( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + trigger_name: str, + create_update_sql_trigger_parameters: Union[_models.SqlTriggerCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_sql_trigger_parameters, (IOBase, bytes)): + _content = create_update_sql_trigger_parameters + else: + _json = self._serialize.body(create_update_sql_trigger_parameters, "SqlTriggerCreateUpdateParameters") + + _request = build_create_update_sql_trigger_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + trigger_name=trigger_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_update_sql_trigger( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + trigger_name: str, + create_update_sql_trigger_parameters: _models.SqlTriggerCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.SqlTriggerGetResults]: + """Create or update an Azure Cosmos DB SQL trigger. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param trigger_name: Cosmos DB trigger name. Required. + :type trigger_name: str + :param create_update_sql_trigger_parameters: The parameters to provide for the current SQL + trigger. Required. + :type create_update_sql_trigger_parameters: + ~azure.mgmt.cosmosdb.models.SqlTriggerCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either SqlTriggerGetResults or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlTriggerGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_update_sql_trigger( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + trigger_name: str, + create_update_sql_trigger_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.SqlTriggerGetResults]: + """Create or update an Azure Cosmos DB SQL trigger. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param trigger_name: Cosmos DB trigger name. Required. + :type trigger_name: str + :param create_update_sql_trigger_parameters: The parameters to provide for the current SQL + trigger. Required. + :type create_update_sql_trigger_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either SqlTriggerGetResults or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlTriggerGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_update_sql_trigger( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + trigger_name: str, + create_update_sql_trigger_parameters: Union[_models.SqlTriggerCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.SqlTriggerGetResults]: + """Create or update an Azure Cosmos DB SQL trigger. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param trigger_name: Cosmos DB trigger name. Required. + :type trigger_name: str + :param create_update_sql_trigger_parameters: The parameters to provide for the current SQL + trigger. Is either a SqlTriggerCreateUpdateParameters type or a IO[bytes] type. Required. + :type create_update_sql_trigger_parameters: + ~azure.mgmt.cosmosdb.models.SqlTriggerCreateUpdateParameters or IO[bytes] + :return: An instance of LROPoller that returns either SqlTriggerGetResults or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlTriggerGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.SqlTriggerGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_update_sql_trigger_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + trigger_name=trigger_name, + create_update_sql_trigger_parameters=create_update_sql_trigger_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("SqlTriggerGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.SqlTriggerGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.SqlTriggerGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_sql_trigger_initial( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + trigger_name: str, + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_sql_trigger_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + trigger_name=trigger_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete_sql_trigger( + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + trigger_name: str, + **kwargs: Any + ) -> LROPoller[None]: + """Deletes an existing Azure Cosmos DB SQL trigger. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param trigger_name: Cosmos DB trigger name. Required. + :type trigger_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_sql_trigger_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + trigger_name=trigger_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def get_sql_role_definition( + self, role_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any + ) -> _models.SqlRoleDefinitionGetResults: + """Retrieves the properties of an existing Azure Cosmos DB SQL Role Definition with the given Id. + + :param role_definition_id: The GUID for the Role Definition. Required. + :type role_definition_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: SqlRoleDefinitionGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.SqlRoleDefinitionGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SqlRoleDefinitionGetResults] = kwargs.pop("cls", None) + + _request = build_get_sql_role_definition_request( + role_definition_id=role_definition_id, + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("SqlRoleDefinitionGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_update_sql_role_definition_initial( # pylint: disable=name-too-long + self, + role_definition_id: str, + resource_group_name: str, + account_name: str, + create_update_sql_role_definition_parameters: Union[_models.SqlRoleDefinitionCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_sql_role_definition_parameters, (IOBase, bytes)): + _content = create_update_sql_role_definition_parameters + else: + _json = self._serialize.body( + create_update_sql_role_definition_parameters, "SqlRoleDefinitionCreateUpdateParameters" + ) + + _request = build_create_update_sql_role_definition_request( + role_definition_id=role_definition_id, + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_update_sql_role_definition( + self, + role_definition_id: str, + resource_group_name: str, + account_name: str, + create_update_sql_role_definition_parameters: _models.SqlRoleDefinitionCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.SqlRoleDefinitionGetResults]: + """Creates or updates an Azure Cosmos DB SQL Role Definition. + + :param role_definition_id: The GUID for the Role Definition. Required. + :type role_definition_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param create_update_sql_role_definition_parameters: The properties required to create or + update a Role Definition. Required. + :type create_update_sql_role_definition_parameters: + ~azure.mgmt.cosmosdb.models.SqlRoleDefinitionCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either SqlRoleDefinitionGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlRoleDefinitionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_update_sql_role_definition( + self, + role_definition_id: str, + resource_group_name: str, + account_name: str, + create_update_sql_role_definition_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.SqlRoleDefinitionGetResults]: + """Creates or updates an Azure Cosmos DB SQL Role Definition. + + :param role_definition_id: The GUID for the Role Definition. Required. + :type role_definition_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param create_update_sql_role_definition_parameters: The properties required to create or + update a Role Definition. Required. + :type create_update_sql_role_definition_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either SqlRoleDefinitionGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlRoleDefinitionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_update_sql_role_definition( + self, + role_definition_id: str, + resource_group_name: str, + account_name: str, + create_update_sql_role_definition_parameters: Union[_models.SqlRoleDefinitionCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.SqlRoleDefinitionGetResults]: + """Creates or updates an Azure Cosmos DB SQL Role Definition. + + :param role_definition_id: The GUID for the Role Definition. Required. + :type role_definition_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param create_update_sql_role_definition_parameters: The properties required to create or + update a Role Definition. Is either a SqlRoleDefinitionCreateUpdateParameters type or a + IO[bytes] type. Required. + :type create_update_sql_role_definition_parameters: + ~azure.mgmt.cosmosdb.models.SqlRoleDefinitionCreateUpdateParameters or IO[bytes] + :return: An instance of LROPoller that returns either SqlRoleDefinitionGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlRoleDefinitionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.SqlRoleDefinitionGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_update_sql_role_definition_initial( + role_definition_id=role_definition_id, + resource_group_name=resource_group_name, + account_name=account_name, + create_update_sql_role_definition_parameters=create_update_sql_role_definition_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("SqlRoleDefinitionGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.SqlRoleDefinitionGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.SqlRoleDefinitionGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_sql_role_definition_initial( + self, role_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_sql_role_definition_request( + role_definition_id=role_definition_id, + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete_sql_role_definition( + self, role_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Deletes an existing Azure Cosmos DB SQL Role Definition. + + :param role_definition_id: The GUID for the Role Definition. Required. + :type role_definition_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_sql_role_definition_initial( + role_definition_id=role_definition_id, + resource_group_name=resource_group_name, + account_name=account_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def list_sql_role_definitions( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> Iterable["_models.SqlRoleDefinitionGetResults"]: + """Retrieves the list of all Azure Cosmos DB SQL Role Definitions. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either SqlRoleDefinitionGetResults or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.SqlRoleDefinitionGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SqlRoleDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_sql_role_definitions_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("SqlRoleDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get_sql_role_assignment( + self, role_assignment_id: str, resource_group_name: str, account_name: str, **kwargs: Any + ) -> _models.SqlRoleAssignmentGetResults: + """Retrieves the properties of an existing Azure Cosmos DB SQL Role Assignment with the given Id. + + :param role_assignment_id: The GUID for the Role Assignment. Required. + :type role_assignment_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: SqlRoleAssignmentGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.SqlRoleAssignmentGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SqlRoleAssignmentGetResults] = kwargs.pop("cls", None) + + _request = build_get_sql_role_assignment_request( + role_assignment_id=role_assignment_id, + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("SqlRoleAssignmentGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_update_sql_role_assignment_initial( # pylint: disable=name-too-long + self, + role_assignment_id: str, + resource_group_name: str, + account_name: str, + create_update_sql_role_assignment_parameters: Union[_models.SqlRoleAssignmentCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_sql_role_assignment_parameters, (IOBase, bytes)): + _content = create_update_sql_role_assignment_parameters + else: + _json = self._serialize.body( + create_update_sql_role_assignment_parameters, "SqlRoleAssignmentCreateUpdateParameters" + ) + + _request = build_create_update_sql_role_assignment_request( + role_assignment_id=role_assignment_id, + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_update_sql_role_assignment( + self, + role_assignment_id: str, + resource_group_name: str, + account_name: str, + create_update_sql_role_assignment_parameters: _models.SqlRoleAssignmentCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.SqlRoleAssignmentGetResults]: + """Creates or updates an Azure Cosmos DB SQL Role Assignment. + + :param role_assignment_id: The GUID for the Role Assignment. Required. + :type role_assignment_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param create_update_sql_role_assignment_parameters: The properties required to create or + update a Role Assignment. Required. + :type create_update_sql_role_assignment_parameters: + ~azure.mgmt.cosmosdb.models.SqlRoleAssignmentCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either SqlRoleAssignmentGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlRoleAssignmentGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_update_sql_role_assignment( + self, + role_assignment_id: str, + resource_group_name: str, + account_name: str, + create_update_sql_role_assignment_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.SqlRoleAssignmentGetResults]: + """Creates or updates an Azure Cosmos DB SQL Role Assignment. + + :param role_assignment_id: The GUID for the Role Assignment. Required. + :type role_assignment_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param create_update_sql_role_assignment_parameters: The properties required to create or + update a Role Assignment. Required. + :type create_update_sql_role_assignment_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either SqlRoleAssignmentGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlRoleAssignmentGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_update_sql_role_assignment( + self, + role_assignment_id: str, + resource_group_name: str, + account_name: str, + create_update_sql_role_assignment_parameters: Union[_models.SqlRoleAssignmentCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.SqlRoleAssignmentGetResults]: + """Creates or updates an Azure Cosmos DB SQL Role Assignment. + + :param role_assignment_id: The GUID for the Role Assignment. Required. + :type role_assignment_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param create_update_sql_role_assignment_parameters: The properties required to create or + update a Role Assignment. Is either a SqlRoleAssignmentCreateUpdateParameters type or a + IO[bytes] type. Required. + :type create_update_sql_role_assignment_parameters: + ~azure.mgmt.cosmosdb.models.SqlRoleAssignmentCreateUpdateParameters or IO[bytes] + :return: An instance of LROPoller that returns either SqlRoleAssignmentGetResults or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.SqlRoleAssignmentGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.SqlRoleAssignmentGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_update_sql_role_assignment_initial( + role_assignment_id=role_assignment_id, + resource_group_name=resource_group_name, + account_name=account_name, + create_update_sql_role_assignment_parameters=create_update_sql_role_assignment_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("SqlRoleAssignmentGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.SqlRoleAssignmentGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.SqlRoleAssignmentGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_sql_role_assignment_initial( + self, role_assignment_id: str, resource_group_name: str, account_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_sql_role_assignment_request( + role_assignment_id=role_assignment_id, + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete_sql_role_assignment( + self, role_assignment_id: str, resource_group_name: str, account_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Deletes an existing Azure Cosmos DB SQL Role Assignment. + + :param role_assignment_id: The GUID for the Role Assignment. Required. + :type role_assignment_id: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_sql_role_assignment_initial( + role_assignment_id=role_assignment_id, + resource_group_name=resource_group_name, + account_name=account_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def list_sql_role_assignments( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> Iterable["_models.SqlRoleAssignmentGetResults"]: + """Retrieves the list of all Azure Cosmos DB SQL Role Assignments. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either SqlRoleAssignmentGetResults or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.SqlRoleAssignmentGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SqlRoleAssignmentListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_sql_role_assignments_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("SqlRoleAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + def _retrieve_continuous_backup_information_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(location, (IOBase, bytes)): + _content = location + else: + _json = self._serialize.body(location, "ContinuousBackupRestoreLocation") + + _request = build_retrieve_continuous_backup_information_request( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + location: _models.ContinuousBackupRestoreLocation, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.BackupInformation]: + """Retrieves continuous backup information for a container resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param location: The name of the continuous backup restore location. Required. + :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either BackupInformation or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + location: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.BackupInformation]: + """Retrieves continuous backup information for a container resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param location: The name of the continuous backup restore location. Required. + :type location: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either BackupInformation or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + database_name: str, + container_name: str, + location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.BackupInformation]: + """Retrieves continuous backup information for a container resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param database_name: Cosmos DB database name. Required. + :type database_name: str + :param container_name: Cosmos DB container name. Required. + :type container_name: str + :param location: The name of the continuous backup restore location. Is either a + ContinuousBackupRestoreLocation type or a IO[bytes] type. Required. + :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation or IO[bytes] + :return: An instance of LROPoller that returns either BackupInformation or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.BackupInformation] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._retrieve_continuous_backup_information_initial( + resource_group_name=resource_group_name, + account_name=account_name, + database_name=database_name, + container_name=container_name, + location=location, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("BackupInformation", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.BackupInformation].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.BackupInformation]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_table_resources_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_table_resources_operations.py index 615d86cee8d..230857cc8e4 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_table_resources_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_table_resources_operations.py @@ -1,1588 +1,1588 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.arm_polling import ARMPolling - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_tables_request( - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/tables", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_table_request( - resource_group_name: str, account_name: str, table_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/tables/{tableName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "tableName": _SERIALIZER.url("table_name", table_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_update_table_request( - resource_group_name: str, account_name: str, table_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/tables/{tableName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "tableName": _SERIALIZER.url("table_name", table_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_table_request( - resource_group_name: str, account_name: str, table_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/tables/{tableName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "tableName": _SERIALIZER.url("table_name", table_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) - - -def build_get_table_throughput_request( - resource_group_name: str, account_name: str, table_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/tables/{tableName}/throughputSettings/default", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "tableName": _SERIALIZER.url("table_name", table_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_update_table_throughput_request( - resource_group_name: str, account_name: str, table_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/tables/{tableName}/throughputSettings/default", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "tableName": _SERIALIZER.url("table_name", table_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_migrate_table_to_autoscale_request( - resource_group_name: str, account_name: str, table_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/tables/{tableName}/throughputSettings/default/migrateToAutoscale", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "tableName": _SERIALIZER.url("table_name", table_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_migrate_table_to_manual_throughput_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, table_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/tables/{tableName}/throughputSettings/default/migrateToManualThroughput", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "tableName": _SERIALIZER.url("table_name", table_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_retrieve_continuous_backup_information_request( # pylint: disable=name-too-long - resource_group_name: str, account_name: str, table_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/tables/{tableName}/retrieveContinuousBackupInformation", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "accountName": _SERIALIZER.url( - "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" - ), - "tableName": _SERIALIZER.url("table_name", table_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -class TableResourcesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`table_resources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_tables( - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> Iterable["_models.TableGetResults"]: - """Lists the Tables under an existing Azure Cosmos DB database account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :return: An iterator like instance of either TableGetResults or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.TableGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.TableListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_tables_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("TableListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get_table( - self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any - ) -> _models.TableGetResults: - """Gets the Tables under an existing Azure Cosmos DB database account with the provided name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :return: TableGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.TableGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.TableGetResults] = kwargs.pop("cls", None) - - _request = build_get_table_request( - resource_group_name=resource_group_name, - account_name=account_name, - table_name=table_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("TableGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _create_update_table_initial( - self, - resource_group_name: str, - account_name: str, - table_name: str, - create_update_table_parameters: Union[_models.TableCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_update_table_parameters, (IOBase, bytes)): - _content = create_update_table_parameters - else: - _json = self._serialize.body(create_update_table_parameters, "TableCreateUpdateParameters") - - _request = build_create_update_table_request( - resource_group_name=resource_group_name, - account_name=account_name, - table_name=table_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_update_table( - self, - resource_group_name: str, - account_name: str, - table_name: str, - create_update_table_parameters: _models.TableCreateUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.TableGetResults]: - """Create or update an Azure Cosmos DB Table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :param create_update_table_parameters: The parameters to provide for the current Table. - Required. - :type create_update_table_parameters: ~azure.mgmt.cosmosdb.models.TableCreateUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either TableGetResults or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.TableGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_update_table( - self, - resource_group_name: str, - account_name: str, - table_name: str, - create_update_table_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.TableGetResults]: - """Create or update an Azure Cosmos DB Table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :param create_update_table_parameters: The parameters to provide for the current Table. - Required. - :type create_update_table_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either TableGetResults or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.TableGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_update_table( - self, - resource_group_name: str, - account_name: str, - table_name: str, - create_update_table_parameters: Union[_models.TableCreateUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.TableGetResults]: - """Create or update an Azure Cosmos DB Table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :param create_update_table_parameters: The parameters to provide for the current Table. Is - either a TableCreateUpdateParameters type or a IO[bytes] type. Required. - :type create_update_table_parameters: ~azure.mgmt.cosmosdb.models.TableCreateUpdateParameters - or IO[bytes] - :return: An instance of LROPoller that returns either TableGetResults or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.TableGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.TableGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_update_table_initial( - resource_group_name=resource_group_name, - account_name=account_name, - table_name=table_name, - create_update_table_parameters=create_update_table_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("TableGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.TableGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.TableGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _delete_table_initial( - self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_table_request( - resource_group_name=resource_group_name, - account_name=account_name, - table_name=table_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete_table( - self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any - ) -> LROPoller[None]: - """Deletes an existing Azure Cosmos DB Table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_table_initial( - resource_group_name=resource_group_name, - account_name=account_name, - table_name=table_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace - def get_table_throughput( - self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any - ) -> _models.ThroughputSettingsGetResults: - """Gets the RUs per second of the Table under an existing Azure Cosmos DB database account with - the provided name. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :return: ThroughputSettingsGetResults or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - - _request = build_get_table_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - table_name=table_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _update_table_throughput_initial( - self, - resource_group_name: str, - account_name: str, - table_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(update_throughput_parameters, (IOBase, bytes)): - _content = update_throughput_parameters - else: - _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") - - _request = build_update_table_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - table_name=table_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_update_table_throughput( - self, - resource_group_name: str, - account_name: str, - table_name: str, - update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :param update_throughput_parameters: The parameters to provide for the RUs per second of the - current Table. Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_update_table_throughput( - self, - resource_group_name: str, - account_name: str, - table_name: str, - update_throughput_parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :param update_throughput_parameters: The parameters to provide for the RUs per second of the - current Table. Required. - :type update_throughput_parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_update_table_throughput( - self, - resource_group_name: str, - account_name: str, - table_name: str, - update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Update RUs per second of an Azure Cosmos DB Table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :param update_throughput_parameters: The parameters to provide for the RUs per second of the - current Table. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] type. - Required. - :type update_throughput_parameters: - ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._update_table_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - table_name=table_name, - update_throughput_parameters=update_throughput_parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _migrate_table_to_autoscale_initial( - self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_table_to_autoscale_request( - resource_group_name=resource_group_name, - account_name=account_name, - table_name=table_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_migrate_table_to_autoscale( - self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB Table from manual throughput to autoscale. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._migrate_table_to_autoscale_initial( - resource_group_name=resource_group_name, - account_name=account_name, - table_name=table_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _migrate_table_to_manual_throughput_initial( # pylint: disable=name-too-long - self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_migrate_table_to_manual_throughput_request( - resource_group_name=resource_group_name, - account_name=account_name, - table_name=table_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_migrate_table_to_manual_throughput( - self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any - ) -> LROPoller[_models.ThroughputSettingsGetResults]: - """Migrate an Azure Cosmos DB Table from autoscale to manual throughput. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._migrate_table_to_manual_throughput_initial( - resource_group_name=resource_group_name, - account_name=account_name, - table_name=table_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputSettingsGetResults]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _retrieve_continuous_backup_information_initial( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - table_name: str, - location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(location, (IOBase, bytes)): - _content = location - else: - _json = self._serialize.body(location, "ContinuousBackupRestoreLocation") - - _request = build_retrieve_continuous_backup_information_request( - resource_group_name=resource_group_name, - account_name=account_name, - table_name=table_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - table_name: str, - location: _models.ContinuousBackupRestoreLocation, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.BackupInformation]: - """Retrieves continuous backup information for a table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :param location: The name of the continuous backup restore location. Required. - :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either BackupInformation or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - table_name: str, - location: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.BackupInformation]: - """Retrieves continuous backup information for a table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :param location: The name of the continuous backup restore location. Required. - :type location: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either BackupInformation or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long - self, - resource_group_name: str, - account_name: str, - table_name: str, - location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.BackupInformation]: - """Retrieves continuous backup information for a table. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param account_name: Cosmos DB database account name. Required. - :type account_name: str - :param table_name: Cosmos DB table name. Required. - :type table_name: str - :param location: The name of the continuous backup restore location. Is either a - ContinuousBackupRestoreLocation type or a IO[bytes] type. Required. - :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation or IO[bytes] - :return: An instance of LROPoller that returns either BackupInformation or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.BackupInformation] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._retrieve_continuous_backup_information_initial( - resource_group_name=resource_group_name, - account_name=account_name, - table_name=table_name, - location=location, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("BackupInformation", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.BackupInformation].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.BackupInformation]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_tables_request( + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/tables", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_table_request( + resource_group_name: str, account_name: str, table_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/tables/{tableName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "tableName": _SERIALIZER.url("table_name", table_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_update_table_request( + resource_group_name: str, account_name: str, table_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/tables/{tableName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "tableName": _SERIALIZER.url("table_name", table_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_table_request( + resource_group_name: str, account_name: str, table_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/tables/{tableName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "tableName": _SERIALIZER.url("table_name", table_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_get_table_throughput_request( + resource_group_name: str, account_name: str, table_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/tables/{tableName}/throughputSettings/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "tableName": _SERIALIZER.url("table_name", table_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_table_throughput_request( + resource_group_name: str, account_name: str, table_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/tables/{tableName}/throughputSettings/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "tableName": _SERIALIZER.url("table_name", table_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_migrate_table_to_autoscale_request( + resource_group_name: str, account_name: str, table_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/tables/{tableName}/throughputSettings/default/migrateToAutoscale", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "tableName": _SERIALIZER.url("table_name", table_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_migrate_table_to_manual_throughput_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, table_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/tables/{tableName}/throughputSettings/default/migrateToManualThroughput", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "tableName": _SERIALIZER.url("table_name", table_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_retrieve_continuous_backup_information_request( # pylint: disable=name-too-long + resource_group_name: str, account_name: str, table_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/tables/{tableName}/retrieveContinuousBackupInformation", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=50, min_length=3, pattern=r"^[a-z0-9]+(-[a-z0-9]+)*" + ), + "tableName": _SERIALIZER.url("table_name", table_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class TableResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`table_resources` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_tables( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> Iterable["_models.TableGetResults"]: + """Lists the Tables under an existing Azure Cosmos DB database account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :return: An iterator like instance of either TableGetResults or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.TableGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.TableListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_tables_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("TableListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get_table( + self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any + ) -> _models.TableGetResults: + """Gets the Tables under an existing Azure Cosmos DB database account with the provided name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :return: TableGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.TableGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.TableGetResults] = kwargs.pop("cls", None) + + _request = build_get_table_request( + resource_group_name=resource_group_name, + account_name=account_name, + table_name=table_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("TableGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_update_table_initial( + self, + resource_group_name: str, + account_name: str, + table_name: str, + create_update_table_parameters: Union[_models.TableCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_update_table_parameters, (IOBase, bytes)): + _content = create_update_table_parameters + else: + _json = self._serialize.body(create_update_table_parameters, "TableCreateUpdateParameters") + + _request = build_create_update_table_request( + resource_group_name=resource_group_name, + account_name=account_name, + table_name=table_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_update_table( + self, + resource_group_name: str, + account_name: str, + table_name: str, + create_update_table_parameters: _models.TableCreateUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.TableGetResults]: + """Create or update an Azure Cosmos DB Table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :param create_update_table_parameters: The parameters to provide for the current Table. + Required. + :type create_update_table_parameters: ~azure.mgmt.cosmosdb.models.TableCreateUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either TableGetResults or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.TableGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_update_table( + self, + resource_group_name: str, + account_name: str, + table_name: str, + create_update_table_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.TableGetResults]: + """Create or update an Azure Cosmos DB Table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :param create_update_table_parameters: The parameters to provide for the current Table. + Required. + :type create_update_table_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either TableGetResults or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.TableGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_update_table( + self, + resource_group_name: str, + account_name: str, + table_name: str, + create_update_table_parameters: Union[_models.TableCreateUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.TableGetResults]: + """Create or update an Azure Cosmos DB Table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :param create_update_table_parameters: The parameters to provide for the current Table. Is + either a TableCreateUpdateParameters type or a IO[bytes] type. Required. + :type create_update_table_parameters: ~azure.mgmt.cosmosdb.models.TableCreateUpdateParameters + or IO[bytes] + :return: An instance of LROPoller that returns either TableGetResults or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.TableGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.TableGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_update_table_initial( + resource_group_name=resource_group_name, + account_name=account_name, + table_name=table_name, + create_update_table_parameters=create_update_table_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("TableGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.TableGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.TableGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_table_initial( + self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_table_request( + resource_group_name=resource_group_name, + account_name=account_name, + table_name=table_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete_table( + self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Deletes an existing Azure Cosmos DB Table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_table_initial( + resource_group_name=resource_group_name, + account_name=account_name, + table_name=table_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def get_table_throughput( + self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any + ) -> _models.ThroughputSettingsGetResults: + """Gets the RUs per second of the Table under an existing Azure Cosmos DB database account with + the provided name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :return: ThroughputSettingsGetResults or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + + _request = build_get_table_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + table_name=table_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _update_table_throughput_initial( + self, + resource_group_name: str, + account_name: str, + table_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(update_throughput_parameters, (IOBase, bytes)): + _content = update_throughput_parameters + else: + _json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters") + + _request = build_update_table_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + table_name=table_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_update_table_throughput( + self, + resource_group_name: str, + account_name: str, + table_name: str, + update_throughput_parameters: _models.ThroughputSettingsUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :param update_throughput_parameters: The parameters to provide for the RUs per second of the + current Table. Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update_table_throughput( + self, + resource_group_name: str, + account_name: str, + table_name: str, + update_throughput_parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :param update_throughput_parameters: The parameters to provide for the RUs per second of the + current Table. Required. + :type update_throughput_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update_table_throughput( + self, + resource_group_name: str, + account_name: str, + table_name: str, + update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Update RUs per second of an Azure Cosmos DB Table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :param update_throughput_parameters: The parameters to provide for the RUs per second of the + current Table. Is either a ThroughputSettingsUpdateParameters type or a IO[bytes] type. + Required. + :type update_throughput_parameters: + ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO[bytes] + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._update_table_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + table_name=table_name, + update_throughput_parameters=update_throughput_parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _migrate_table_to_autoscale_initial( + self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_table_to_autoscale_request( + resource_group_name=resource_group_name, + account_name=account_name, + table_name=table_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_migrate_table_to_autoscale( + self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB Table from manual throughput to autoscale. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._migrate_table_to_autoscale_initial( + resource_group_name=resource_group_name, + account_name=account_name, + table_name=table_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _migrate_table_to_manual_throughput_initial( # pylint: disable=name-too-long + self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_migrate_table_to_manual_throughput_request( + resource_group_name=resource_group_name, + account_name=account_name, + table_name=table_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_migrate_table_to_manual_throughput( + self, resource_group_name: str, account_name: str, table_name: str, **kwargs: Any + ) -> LROPoller[_models.ThroughputSettingsGetResults]: + """Migrate an Azure Cosmos DB Table from autoscale to manual throughput. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the + result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._migrate_table_to_manual_throughput_initial( + resource_group_name=resource_group_name, + account_name=account_name, + table_name=table_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputSettingsGetResults].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputSettingsGetResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _retrieve_continuous_backup_information_initial( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + table_name: str, + location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(location, (IOBase, bytes)): + _content = location + else: + _json = self._serialize.body(location, "ContinuousBackupRestoreLocation") + + _request = build_retrieve_continuous_backup_information_request( + resource_group_name=resource_group_name, + account_name=account_name, + table_name=table_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + table_name: str, + location: _models.ContinuousBackupRestoreLocation, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.BackupInformation]: + """Retrieves continuous backup information for a table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :param location: The name of the continuous backup restore location. Required. + :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either BackupInformation or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + table_name: str, + location: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.BackupInformation]: + """Retrieves continuous backup information for a table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :param location: The name of the continuous backup restore location. Required. + :type location: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either BackupInformation or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_retrieve_continuous_backup_information( # pylint: disable=name-too-long + self, + resource_group_name: str, + account_name: str, + table_name: str, + location: Union[_models.ContinuousBackupRestoreLocation, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.BackupInformation]: + """Retrieves continuous backup information for a table. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: Cosmos DB database account name. Required. + :type account_name: str + :param table_name: Cosmos DB table name. Required. + :type table_name: str + :param location: The name of the continuous backup restore location. Is either a + ContinuousBackupRestoreLocation type or a IO[bytes] type. Required. + :type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation or IO[bytes] + :return: An instance of LROPoller that returns either BackupInformation or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.BackupInformation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.BackupInformation] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._retrieve_continuous_backup_information_initial( + resource_group_name=resource_group_name, + account_name=account_name, + table_name=table_name, + location=location, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("BackupInformation", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.BackupInformation].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.BackupInformation]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_throughput_pool_account_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_throughput_pool_account_operations.py index 66ea2732a49..336043f5cd5 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_throughput_pool_account_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_throughput_pool_account_operations.py @@ -1,617 +1,617 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Iterator, Optional, Type, TypeVar, Union, cast, overload - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.arm_polling import ARMPolling - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_request( - resource_group_name: str, - throughput_pool_name: str, - throughput_pool_account_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/throughputPools/{throughputPoolName}/throughputPoolAccounts/{throughputPoolAccountName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "throughputPoolName": _SERIALIZER.url( - "throughput_pool_name", - throughput_pool_name, - "str", - max_length=50, - min_length=3, - pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", - ), - "throughputPoolAccountName": _SERIALIZER.url( - "throughput_pool_account_name", - throughput_pool_account_name, - "str", - max_length=50, - min_length=3, - pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_request( - resource_group_name: str, - throughput_pool_name: str, - throughput_pool_account_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/throughputPools/{throughputPoolName}/throughputPoolAccounts/{throughputPoolAccountName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "throughputPoolName": _SERIALIZER.url( - "throughput_pool_name", - throughput_pool_name, - "str", - max_length=50, - min_length=3, - pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", - ), - "throughputPoolAccountName": _SERIALIZER.url( - "throughput_pool_account_name", - throughput_pool_account_name, - "str", - max_length=50, - min_length=3, - pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - resource_group_name: str, - throughput_pool_name: str, - throughput_pool_account_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/throughputPools/{throughputPoolName}/throughputPoolAccounts/{throughputPoolAccountName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "throughputPoolName": _SERIALIZER.url( - "throughput_pool_name", - throughput_pool_name, - "str", - max_length=50, - min_length=3, - pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", - ), - "throughputPoolAccountName": _SERIALIZER.url( - "throughput_pool_account_name", - throughput_pool_account_name, - "str", - max_length=50, - min_length=3, - pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -class ThroughputPoolAccountOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`throughput_pool_account` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def get( - self, resource_group_name: str, throughput_pool_name: str, throughput_pool_account_name: str, **kwargs: Any - ) -> _models.ThroughputPoolAccountResource: - """Retrieves the properties of an existing Azure Cosmos DB Throughput Pool. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. - :type throughput_pool_name: str - :param throughput_pool_account_name: Cosmos DB global database account in a Throughput Pool. - Required. - :type throughput_pool_account_name: str - :return: ThroughputPoolAccountResource or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ThroughputPoolAccountResource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputPoolAccountResource] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - throughput_pool_name=throughput_pool_name, - throughput_pool_account_name=throughput_pool_account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ThroughputPoolAccountResource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _create_initial( - self, - resource_group_name: str, - throughput_pool_name: str, - throughput_pool_account_name: str, - body: Union[_models.ThroughputPoolAccountResource, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _json = self._serialize.body(body, "ThroughputPoolAccountResource") - - _request = build_create_request( - resource_group_name=resource_group_name, - throughput_pool_name=throughput_pool_name, - throughput_pool_account_name=throughput_pool_account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create( - self, - resource_group_name: str, - throughput_pool_name: str, - throughput_pool_account_name: str, - body: _models.ThroughputPoolAccountResource, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ThroughputPoolAccountResource]: - """Creates or updates an Azure Cosmos DB ThroughputPool account. The "Update" method is preferred - when performing updates on an account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. - :type throughput_pool_name: str - :param throughput_pool_account_name: Cosmos DB global database account in a Throughput Pool. - Required. - :type throughput_pool_account_name: str - :param body: The parameters to provide for the current ThroughputPoolAccount. Required. - :type body: ~azure.mgmt.cosmosdb.models.ThroughputPoolAccountResource - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ThroughputPoolAccountResource or the - result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolAccountResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create( - self, - resource_group_name: str, - throughput_pool_name: str, - throughput_pool_account_name: str, - body: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ThroughputPoolAccountResource]: - """Creates or updates an Azure Cosmos DB ThroughputPool account. The "Update" method is preferred - when performing updates on an account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. - :type throughput_pool_name: str - :param throughput_pool_account_name: Cosmos DB global database account in a Throughput Pool. - Required. - :type throughput_pool_account_name: str - :param body: The parameters to provide for the current ThroughputPoolAccount. Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ThroughputPoolAccountResource or the - result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolAccountResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create( - self, - resource_group_name: str, - throughput_pool_name: str, - throughput_pool_account_name: str, - body: Union[_models.ThroughputPoolAccountResource, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.ThroughputPoolAccountResource]: - """Creates or updates an Azure Cosmos DB ThroughputPool account. The "Update" method is preferred - when performing updates on an account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. - :type throughput_pool_name: str - :param throughput_pool_account_name: Cosmos DB global database account in a Throughput Pool. - Required. - :type throughput_pool_account_name: str - :param body: The parameters to provide for the current ThroughputPoolAccount. Is either a - ThroughputPoolAccountResource type or a IO[bytes] type. Required. - :type body: ~azure.mgmt.cosmosdb.models.ThroughputPoolAccountResource or IO[bytes] - :return: An instance of LROPoller that returns either ThroughputPoolAccountResource or the - result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolAccountResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ThroughputPoolAccountResource] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_initial( - resource_group_name=resource_group_name, - throughput_pool_name=throughput_pool_name, - throughput_pool_account_name=throughput_pool_account_name, - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputPoolAccountResource", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputPoolAccountResource].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputPoolAccountResource]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _delete_initial( - self, resource_group_name: str, throughput_pool_name: str, throughput_pool_account_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - throughput_pool_name=throughput_pool_name, - throughput_pool_account_name=throughput_pool_account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete( - self, resource_group_name: str, throughput_pool_name: str, throughput_pool_account_name: str, **kwargs: Any - ) -> LROPoller[None]: - """Removes an existing Azure Cosmos DB database account from a throughput pool. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. - :type throughput_pool_name: str - :param throughput_pool_account_name: Cosmos DB global database account in a Throughput Pool. - Required. - :type throughput_pool_account_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_initial( - resource_group_name=resource_group_name, - throughput_pool_name=throughput_pool_name, - throughput_pool_account_name=throughput_pool_account_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterator, Optional, Type, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request( + resource_group_name: str, + throughput_pool_name: str, + throughput_pool_account_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/throughputPools/{throughputPoolName}/throughputPoolAccounts/{throughputPoolAccountName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "throughputPoolName": _SERIALIZER.url( + "throughput_pool_name", + throughput_pool_name, + "str", + max_length=50, + min_length=3, + pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", + ), + "throughputPoolAccountName": _SERIALIZER.url( + "throughput_pool_account_name", + throughput_pool_account_name, + "str", + max_length=50, + min_length=3, + pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_request( + resource_group_name: str, + throughput_pool_name: str, + throughput_pool_account_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/throughputPools/{throughputPoolName}/throughputPoolAccounts/{throughputPoolAccountName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "throughputPoolName": _SERIALIZER.url( + "throughput_pool_name", + throughput_pool_name, + "str", + max_length=50, + min_length=3, + pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", + ), + "throughputPoolAccountName": _SERIALIZER.url( + "throughput_pool_account_name", + throughput_pool_account_name, + "str", + max_length=50, + min_length=3, + pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, + throughput_pool_name: str, + throughput_pool_account_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/throughputPools/{throughputPoolName}/throughputPoolAccounts/{throughputPoolAccountName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "throughputPoolName": _SERIALIZER.url( + "throughput_pool_name", + throughput_pool_name, + "str", + max_length=50, + min_length=3, + pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", + ), + "throughputPoolAccountName": _SERIALIZER.url( + "throughput_pool_account_name", + throughput_pool_account_name, + "str", + max_length=50, + min_length=3, + pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +class ThroughputPoolAccountOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`throughput_pool_account` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get( + self, resource_group_name: str, throughput_pool_name: str, throughput_pool_account_name: str, **kwargs: Any + ) -> _models.ThroughputPoolAccountResource: + """Retrieves the properties of an existing Azure Cosmos DB Throughput Pool. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. + :type throughput_pool_name: str + :param throughput_pool_account_name: Cosmos DB global database account in a Throughput Pool. + Required. + :type throughput_pool_account_name: str + :return: ThroughputPoolAccountResource or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ThroughputPoolAccountResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputPoolAccountResource] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + throughput_pool_name=throughput_pool_name, + throughput_pool_account_name=throughput_pool_account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ThroughputPoolAccountResource", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_initial( + self, + resource_group_name: str, + throughput_pool_name: str, + throughput_pool_account_name: str, + body: Union[_models.ThroughputPoolAccountResource, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "ThroughputPoolAccountResource") + + _request = build_create_request( + resource_group_name=resource_group_name, + throughput_pool_name=throughput_pool_name, + throughput_pool_account_name=throughput_pool_account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create( + self, + resource_group_name: str, + throughput_pool_name: str, + throughput_pool_account_name: str, + body: _models.ThroughputPoolAccountResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ThroughputPoolAccountResource]: + """Creates or updates an Azure Cosmos DB ThroughputPool account. The "Update" method is preferred + when performing updates on an account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. + :type throughput_pool_name: str + :param throughput_pool_account_name: Cosmos DB global database account in a Throughput Pool. + Required. + :type throughput_pool_account_name: str + :param body: The parameters to provide for the current ThroughputPoolAccount. Required. + :type body: ~azure.mgmt.cosmosdb.models.ThroughputPoolAccountResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ThroughputPoolAccountResource or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolAccountResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create( + self, + resource_group_name: str, + throughput_pool_name: str, + throughput_pool_account_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ThroughputPoolAccountResource]: + """Creates or updates an Azure Cosmos DB ThroughputPool account. The "Update" method is preferred + when performing updates on an account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. + :type throughput_pool_name: str + :param throughput_pool_account_name: Cosmos DB global database account in a Throughput Pool. + Required. + :type throughput_pool_account_name: str + :param body: The parameters to provide for the current ThroughputPoolAccount. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ThroughputPoolAccountResource or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolAccountResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create( + self, + resource_group_name: str, + throughput_pool_name: str, + throughput_pool_account_name: str, + body: Union[_models.ThroughputPoolAccountResource, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.ThroughputPoolAccountResource]: + """Creates or updates an Azure Cosmos DB ThroughputPool account. The "Update" method is preferred + when performing updates on an account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. + :type throughput_pool_name: str + :param throughput_pool_account_name: Cosmos DB global database account in a Throughput Pool. + Required. + :type throughput_pool_account_name: str + :param body: The parameters to provide for the current ThroughputPoolAccount. Is either a + ThroughputPoolAccountResource type or a IO[bytes] type. Required. + :type body: ~azure.mgmt.cosmosdb.models.ThroughputPoolAccountResource or IO[bytes] + :return: An instance of LROPoller that returns either ThroughputPoolAccountResource or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolAccountResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ThroughputPoolAccountResource] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_initial( + resource_group_name=resource_group_name, + throughput_pool_name=throughput_pool_name, + throughput_pool_account_name=throughput_pool_account_name, + body=body, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputPoolAccountResource", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputPoolAccountResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputPoolAccountResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_initial( + self, resource_group_name: str, throughput_pool_name: str, throughput_pool_account_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + throughput_pool_name=throughput_pool_name, + throughput_pool_account_name=throughput_pool_account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete( + self, resource_group_name: str, throughput_pool_name: str, throughput_pool_account_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Removes an existing Azure Cosmos DB database account from a throughput pool. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. + :type throughput_pool_name: str + :param throughput_pool_account_name: Cosmos DB global database account in a Throughput Pool. + Required. + :type throughput_pool_account_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + throughput_pool_name=throughput_pool_name, + throughput_pool_account_name=throughput_pool_account_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_throughput_pool_accounts_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_throughput_pool_accounts_operations.py index f5403e6eae8..d81dbef7b82 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_throughput_pool_accounts_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_throughput_pool_accounts_operations.py @@ -1,184 +1,184 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_request( - resource_group_name: str, throughput_pool_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/throughputPools/{throughputPoolName}/throughputPoolAccounts", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "throughputPoolName": _SERIALIZER.url( - "throughput_pool_name", - throughput_pool_name, - "str", - max_length=50, - min_length=3, - pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class ThroughputPoolAccountsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`throughput_pool_accounts` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, resource_group_name: str, throughput_pool_name: str, **kwargs: Any - ) -> Iterable["_models.ThroughputPoolAccountResource"]: - """Lists all the Azure Cosmos DB accounts available under the subscription. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. - :type throughput_pool_name: str - :return: An iterator like instance of either ThroughputPoolAccountResource or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.ThroughputPoolAccountResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputPoolAccountsListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - resource_group_name=resource_group_name, - throughput_pool_name=throughput_pool_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("ThroughputPoolAccountsListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request( + resource_group_name: str, throughput_pool_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/throughputPools/{throughputPoolName}/throughputPoolAccounts", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "throughputPoolName": _SERIALIZER.url( + "throughput_pool_name", + throughput_pool_name, + "str", + max_length=50, + min_length=3, + pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class ThroughputPoolAccountsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`throughput_pool_accounts` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, resource_group_name: str, throughput_pool_name: str, **kwargs: Any + ) -> Iterable["_models.ThroughputPoolAccountResource"]: + """Lists all the Azure Cosmos DB accounts available under the subscription. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. + :type throughput_pool_name: str + :return: An iterator like instance of either ThroughputPoolAccountResource or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.ThroughputPoolAccountResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputPoolAccountsListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + resource_group_name=resource_group_name, + throughput_pool_name=throughput_pool_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ThroughputPoolAccountsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_throughput_pool_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_throughput_pool_operations.py index 322da6ad6e6..fb5bca6d53b 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_throughput_pool_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_throughput_pool_operations.py @@ -1,796 +1,796 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Iterator, Optional, Type, TypeVar, Union, cast, overload - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.arm_polling import ARMPolling - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_request( - resource_group_name: str, throughput_pool_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/throughputPools/{throughputPoolName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "throughputPoolName": _SERIALIZER.url( - "throughput_pool_name", - throughput_pool_name, - "str", - max_length=50, - min_length=3, - pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_or_update_request( - resource_group_name: str, throughput_pool_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/throughputPools/{throughputPoolName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "throughputPoolName": _SERIALIZER.url( - "throughput_pool_name", - throughput_pool_name, - "str", - max_length=50, - min_length=3, - pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_update_request( - resource_group_name: str, throughput_pool_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/throughputPools/{throughputPoolName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "throughputPoolName": _SERIALIZER.url( - "throughput_pool_name", - throughput_pool_name, - "str", - max_length=50, - min_length=3, - pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - resource_group_name: str, throughput_pool_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/throughputPools/{throughputPoolName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "throughputPoolName": _SERIALIZER.url( - "throughput_pool_name", - throughput_pool_name, - "str", - max_length=50, - min_length=3, - pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -class ThroughputPoolOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`throughput_pool` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def get(self, resource_group_name: str, throughput_pool_name: str, **kwargs: Any) -> _models.ThroughputPoolResource: - """Retrieves the properties of an existing Azure Cosmos DB Throughput Pool. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. - :type throughput_pool_name: str - :return: ThroughputPoolResource or the result of cls(response) - :rtype: ~azure.mgmt.cosmosdb.models.ThroughputPoolResource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputPoolResource] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - throughput_pool_name=throughput_pool_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ThroughputPoolResource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _create_or_update_initial( - self, - resource_group_name: str, - throughput_pool_name: str, - body: Union[_models.ThroughputPoolResource, IO[bytes]], - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _json = self._serialize.body(body, "ThroughputPoolResource") - - _request = build_create_or_update_request( - resource_group_name=resource_group_name, - throughput_pool_name=throughput_pool_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_or_update( - self, - resource_group_name: str, - throughput_pool_name: str, - body: _models.ThroughputPoolResource, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ThroughputPoolResource]: - """Creates or updates an Azure Cosmos DB ThroughputPool account. The "Update" method is preferred - when performing updates on an account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. - :type throughput_pool_name: str - :param body: The parameters to provide for the current ThroughputPool. Required. - :type body: ~azure.mgmt.cosmosdb.models.ThroughputPoolResource - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ThroughputPoolResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_or_update( - self, - resource_group_name: str, - throughput_pool_name: str, - body: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ThroughputPoolResource]: - """Creates or updates an Azure Cosmos DB ThroughputPool account. The "Update" method is preferred - when performing updates on an account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. - :type throughput_pool_name: str - :param body: The parameters to provide for the current ThroughputPool. Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ThroughputPoolResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_or_update( - self, - resource_group_name: str, - throughput_pool_name: str, - body: Union[_models.ThroughputPoolResource, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.ThroughputPoolResource]: - """Creates or updates an Azure Cosmos DB ThroughputPool account. The "Update" method is preferred - when performing updates on an account. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. - :type throughput_pool_name: str - :param body: The parameters to provide for the current ThroughputPool. Is either a - ThroughputPoolResource type or a IO[bytes] type. Required. - :type body: ~azure.mgmt.cosmosdb.models.ThroughputPoolResource or IO[bytes] - :return: An instance of LROPoller that returns either ThroughputPoolResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ThroughputPoolResource] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_or_update_initial( - resource_group_name=resource_group_name, - throughput_pool_name=throughput_pool_name, - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputPoolResource", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputPoolResource].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputPoolResource]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _update_initial( - self, - resource_group_name: str, - throughput_pool_name: str, - body: Optional[Union[_models.ThroughputPoolUpdate, IO[bytes]]] = None, - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - if body is not None: - _json = self._serialize.body(body, "ThroughputPoolUpdate") - else: - _json = None - - _request = build_update_request( - resource_group_name=resource_group_name, - throughput_pool_name=throughput_pool_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_update( - self, - resource_group_name: str, - throughput_pool_name: str, - body: Optional[_models.ThroughputPoolUpdate] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ThroughputPoolResource]: - """Updates the properties of an existing Azure Cosmos DB Throughput Pool. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. - :type throughput_pool_name: str - :param body: The parameters to provide for the current Throughput Pool. Default value is None. - :type body: ~azure.mgmt.cosmosdb.models.ThroughputPoolUpdate - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ThroughputPoolResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_update( - self, - resource_group_name: str, - throughput_pool_name: str, - body: Optional[IO[bytes]] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ThroughputPoolResource]: - """Updates the properties of an existing Azure Cosmos DB Throughput Pool. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. - :type throughput_pool_name: str - :param body: The parameters to provide for the current Throughput Pool. Default value is None. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either ThroughputPoolResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_update( - self, - resource_group_name: str, - throughput_pool_name: str, - body: Optional[Union[_models.ThroughputPoolUpdate, IO[bytes]]] = None, - **kwargs: Any - ) -> LROPoller[_models.ThroughputPoolResource]: - """Updates the properties of an existing Azure Cosmos DB Throughput Pool. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. - :type throughput_pool_name: str - :param body: The parameters to provide for the current Throughput Pool. Is either a - ThroughputPoolUpdate type or a IO[bytes] type. Default value is None. - :type body: ~azure.mgmt.cosmosdb.models.ThroughputPoolUpdate or IO[bytes] - :return: An instance of LROPoller that returns either ThroughputPoolResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ThroughputPoolResource] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._update_initial( - resource_group_name=resource_group_name, - throughput_pool_name=throughput_pool_name, - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ThroughputPoolResource", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.ThroughputPoolResource].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.ThroughputPoolResource]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _delete_initial(self, resource_group_name: str, throughput_pool_name: str, **kwargs: Any) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - throughput_pool_name=throughput_pool_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202, 204]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("azure-AsyncOperation") - ) - response_headers["location"] = self._deserialize("str", response.headers.get("location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete(self, resource_group_name: str, throughput_pool_name: str, **kwargs: Any) -> LROPoller[None]: - """Deletes an existing Azure Cosmos DB Throughput Pool. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. - :type throughput_pool_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_initial( - resource_group_name=resource_group_name, - throughput_pool_name=throughput_pool_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterator, Optional, Type, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request( + resource_group_name: str, throughput_pool_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/throughputPools/{throughputPoolName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "throughputPoolName": _SERIALIZER.url( + "throughput_pool_name", + throughput_pool_name, + "str", + max_length=50, + min_length=3, + pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request( + resource_group_name: str, throughput_pool_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/throughputPools/{throughputPoolName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "throughputPoolName": _SERIALIZER.url( + "throughput_pool_name", + throughput_pool_name, + "str", + max_length=50, + min_length=3, + pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_request( + resource_group_name: str, throughput_pool_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/throughputPools/{throughputPoolName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "throughputPoolName": _SERIALIZER.url( + "throughput_pool_name", + throughput_pool_name, + "str", + max_length=50, + min_length=3, + pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, throughput_pool_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/throughputPools/{throughputPoolName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "throughputPoolName": _SERIALIZER.url( + "throughput_pool_name", + throughput_pool_name, + "str", + max_length=50, + min_length=3, + pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +class ThroughputPoolOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`throughput_pool` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, resource_group_name: str, throughput_pool_name: str, **kwargs: Any) -> _models.ThroughputPoolResource: + """Retrieves the properties of an existing Azure Cosmos DB Throughput Pool. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. + :type throughput_pool_name: str + :return: ThroughputPoolResource or the result of cls(response) + :rtype: ~azure.mgmt.cosmosdb.models.ThroughputPoolResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputPoolResource] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + throughput_pool_name=throughput_pool_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ThroughputPoolResource", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_or_update_initial( + self, + resource_group_name: str, + throughput_pool_name: str, + body: Union[_models.ThroughputPoolResource, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "ThroughputPoolResource") + + _request = build_create_or_update_request( + resource_group_name=resource_group_name, + throughput_pool_name=throughput_pool_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + throughput_pool_name: str, + body: _models.ThroughputPoolResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ThroughputPoolResource]: + """Creates or updates an Azure Cosmos DB ThroughputPool account. The "Update" method is preferred + when performing updates on an account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. + :type throughput_pool_name: str + :param body: The parameters to provide for the current ThroughputPool. Required. + :type body: ~azure.mgmt.cosmosdb.models.ThroughputPoolResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ThroughputPoolResource or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + throughput_pool_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ThroughputPoolResource]: + """Creates or updates an Azure Cosmos DB ThroughputPool account. The "Update" method is preferred + when performing updates on an account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. + :type throughput_pool_name: str + :param body: The parameters to provide for the current ThroughputPool. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ThroughputPoolResource or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + throughput_pool_name: str, + body: Union[_models.ThroughputPoolResource, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.ThroughputPoolResource]: + """Creates or updates an Azure Cosmos DB ThroughputPool account. The "Update" method is preferred + when performing updates on an account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. + :type throughput_pool_name: str + :param body: The parameters to provide for the current ThroughputPool. Is either a + ThroughputPoolResource type or a IO[bytes] type. Required. + :type body: ~azure.mgmt.cosmosdb.models.ThroughputPoolResource or IO[bytes] + :return: An instance of LROPoller that returns either ThroughputPoolResource or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ThroughputPoolResource] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + throughput_pool_name=throughput_pool_name, + body=body, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputPoolResource", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputPoolResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputPoolResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _update_initial( + self, + resource_group_name: str, + throughput_pool_name: str, + body: Optional[Union[_models.ThroughputPoolUpdate, IO[bytes]]] = None, + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + if body is not None: + _json = self._serialize.body(body, "ThroughputPoolUpdate") + else: + _json = None + + _request = build_update_request( + resource_group_name=resource_group_name, + throughput_pool_name=throughput_pool_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_update( + self, + resource_group_name: str, + throughput_pool_name: str, + body: Optional[_models.ThroughputPoolUpdate] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ThroughputPoolResource]: + """Updates the properties of an existing Azure Cosmos DB Throughput Pool. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. + :type throughput_pool_name: str + :param body: The parameters to provide for the current Throughput Pool. Default value is None. + :type body: ~azure.mgmt.cosmosdb.models.ThroughputPoolUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ThroughputPoolResource or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update( + self, + resource_group_name: str, + throughput_pool_name: str, + body: Optional[IO[bytes]] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ThroughputPoolResource]: + """Updates the properties of an existing Azure Cosmos DB Throughput Pool. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. + :type throughput_pool_name: str + :param body: The parameters to provide for the current Throughput Pool. Default value is None. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ThroughputPoolResource or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update( + self, + resource_group_name: str, + throughput_pool_name: str, + body: Optional[Union[_models.ThroughputPoolUpdate, IO[bytes]]] = None, + **kwargs: Any + ) -> LROPoller[_models.ThroughputPoolResource]: + """Updates the properties of an existing Azure Cosmos DB Throughput Pool. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. + :type throughput_pool_name: str + :param body: The parameters to provide for the current Throughput Pool. Is either a + ThroughputPoolUpdate type or a IO[bytes] type. Default value is None. + :type body: ~azure.mgmt.cosmosdb.models.ThroughputPoolUpdate or IO[bytes] + :return: An instance of LROPoller that returns either ThroughputPoolResource or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ThroughputPoolResource] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._update_initial( + resource_group_name=resource_group_name, + throughput_pool_name=throughput_pool_name, + body=body, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ThroughputPoolResource", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ThroughputPoolResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ThroughputPoolResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_initial(self, resource_group_name: str, throughput_pool_name: str, **kwargs: Any) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + throughput_pool_name=throughput_pool_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("azure-AsyncOperation") + ) + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete(self, resource_group_name: str, throughput_pool_name: str, **kwargs: Any) -> LROPoller[None]: + """Deletes an existing Azure Cosmos DB Throughput Pool. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param throughput_pool_name: Cosmos DB Throughput Pool name. Required. + :type throughput_pool_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + throughput_pool_name=throughput_pool_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_throughput_pools_operations.py b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_throughput_pools_operations.py index d4563d71234..1d8c75844ef 100644 --- a/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_throughput_pools_operations.py +++ b/src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/operations/_throughput_pools_operations.py @@ -1,271 +1,271 @@ -# pylint: disable=too-many-lines,too-many-statements -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/throughputPools") - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_by_resource_group_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/throughputPools", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class ThroughputPoolsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s - :attr:`throughput_pools` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list(self, **kwargs: Any) -> Iterable["_models.ThroughputPoolResource"]: - """Lists all the Azure Cosmos DB Throughput Pools available under the subscription. - - :return: An iterator like instance of either ThroughputPoolResource or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputPoolsListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("ThroughputPoolsListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list_by_resource_group( - self, resource_group_name: str, **kwargs: Any - ) -> Iterable["_models.ThroughputPoolResource"]: - """List all the ThroughputPools in a given resource group. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :return: An iterator like instance of either ThroughputPoolResource or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.ThroughputPoolsListResult] = kwargs.pop("cls", None) - - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_list_by_resource_group_request( - resource_group_name=resource_group_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("ThroughputPoolsListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/throughputPools") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_resource_group_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-09-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/throughputPools", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class ThroughputPoolsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cosmosdb.CosmosDBManagementClient`'s + :attr:`throughput_pools` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.ThroughputPoolResource"]: + """Lists all the Azure Cosmos DB Throughput Pools available under the subscription. + + :return: An iterator like instance of either ThroughputPoolResource or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputPoolsListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ThroughputPoolsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_resource_group( + self, resource_group_name: str, **kwargs: Any + ) -> Iterable["_models.ThroughputPoolResource"]: + """List all the ThroughputPools in a given resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :return: An iterator like instance of either ThroughputPoolResource or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.ThroughputPoolResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ThroughputPoolsListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ThroughputPoolsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data)